■ FormsAuthentication 클래스를 사용해 사용자 로그인을 관리하는 방법을 보여준다.
▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
CREATE TABLE dbo.[User] ( ID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY ,UserID NVARCHAR(50) NOT NULL ,[Password] NVARCHAR(50) NOT NULL ); GO CREATE PROCEDURE dbo.WriteUser @UserID NVARCHAR(25) ,@Password NVARCHAR(20) As INSERT INTO dbo.[User] VALUES (@UserID, @Password); GO CREATE PROCEDURE dbo.ListUser AS SELECT ID ,UserID ,[Password] FROM dbo.[User] ORDER BY ID DESC; GO CREATE PROCEDURE dbo.ViewUser @ID INT AS SELECT ID ,UserID ,[Password] From dbo.[User] WHERE ID = @ID; GO CREATE PROCEDURE dbo.UpdateUser @UserID NVARCHAR(50) ,@Password NVARCHAR(50) ,@ID INT AS BEGIN TRANSACTION; UPDATE dbo.[User] SET UserID = @UserID, [Password] = @Password WHERE ID = @ID; COMMIT TRANSACTION; GO CREATE PROCEDURE dbo.DeleteUser @ID INT AS DELETE dbo.[User] WHERE ID = @ID; GO CREATE PROCEDURE dbo.SearchUser @SearchField NVARCHAR(100) ,@SearchQuery NVARCHAR(100) AS DECLARE @SQL NVARCHAR(1000) SET @SQL = ' SELECT * FROM dbo.[User] WHERE ' + @SearchField + ' LIKE ''%' + @SearchQuery + '%'' ' EXECUTE SP_EXECUTESQL @SQL; GO |
▶ UserModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
namespace TestProject.Models { /// <summary> /// 사용자 모델 /// </summary> public class UserModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 사용자 ID - UserID /// <summary> /// 사용자 ID /// </summary> public string UserID { get; set; } #endregion #region 패스워드 - Password /// <summary> /// 패스워드 /// </summary> public string Password { get; set; } #endregion } } |
▶ UserRepository.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
using System.Data; using System.Data.SqlClient; using System.Web.Configuration; using TestProject.Models; namespace TestProject { /// <summary> /// 사용자 저장소 /// </summary> public class UserRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SQL 연결 /// </summary> private SqlConnection connection; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - UserRepository() /// <summary> /// 생성자 /// </summary> public UserRepository() { this.connection = new SqlConnection(); this.connection.ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 사용자 추가하기 - AddUser(userID, password) /// <summary> /// 사용자 추가하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> public void AddUser(string userID, string password) { SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "WriteUser"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); this.connection.Open(); command.ExecuteNonQuery(); this.connection.Close(); } #endregion #region 사용자 구하기 - GetUser(userID) /// <summary> /// 사용자 구하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <returns>사용자</returns> public UserModel GetUser(string userID) { UserModel user = new UserModel(); SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "SELECT * FROM dbo.[User] WHERE UserID = @UserID"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@UserID", userID); this.connection.Open(); IDataReader reader = command.ExecuteReader(); if(reader.Read()) { user.ID = reader.GetInt32(0); user.UserID = reader.GetString(1); user.Password = reader.GetString(2); } this.connection.Close(); return user; } #endregion #region 사용자 수정하기 - UpdateUser(id, userID, password) /// <summary> /// 사용자 수정하기 /// </summary> /// <param name="id">ID</param> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> public void UpdateUser(int id, string userID, string password) { SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "UpdateUser"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); command.Parameters.AddWithValue("@ID" , id ); this.connection.Open(); command.ExecuteNonQuery(); this.connection.Close(); } #endregion #region 검증된 사용자 여부 구하기 - IsValidUser(userID, password) /// <summary> /// 검증된 사용자 여부 구하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> /// <returns>검증된 사용자 여부</returns> public bool IsValidUser(string userID, string password) { bool result = false; this.connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "SELECT * FROM dbo.[User] WHERE UserID = @UserID AND Password = @Password"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); SqlDataReader reader = command.ExecuteReader(); if(reader.Read()) { result = true; } reader.Close(); this.connection.Close(); return result; } #endregion } } |
▶ Web.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation targetFramework="4.6" debug="true" /> <httpRuntime targetFramework="4.6" /> <authentication mode="Forms"> <forms loginUrl="~/LoginPage.aspx" /> </authentication> </system.web> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> |
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>회원 관리</h1> <h2>메인 페이지</h2> <asp:LoginView ID="loginView" runat="server"> <AnonymousTemplate> <asp:LoginStatus ID="loginStatus1" runat="server" LoginText="로그인" /> | <asp:HyperLink ID="registerHyperLink" runat="server" NavigateUrl="~/RegisterPage.aspx"> 회원가입 </asp:HyperLink> </AnonymousTemplate> <LoggedInTemplate> <asp:LoginStatus ID="loginStatus2" runat="server" LogoutText="로그아웃" Visible="false" /> <a href="LogoutPage.aspx">로그아웃</a> | <asp:HyperLink ID="userHyperLink" runat="server" NavigateUrl="~/UserPage.aspx"> <asp:LoginName ID="loginName" runat="server" /> </asp:HyperLink> </LoggedInTemplate> </asp:LoginView> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
▶ LoginPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LoginPage.aspx.cs" Inherits="TestProject.LoginPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>회원 관리</h1> <h2>로그인</h2> 아이디 : <asp:TextBox ID="userIDTextBox" runat="server" /> <br /> 암호 : <asp:TextBox ID="passwordTextBox" runat="server" TextMode="Password" /> <br /> <asp:Button ID="loginButton" runat="server" Text="로그인" OnClick="loginButton_Click" /> </div> </form> </body> </html> |
▶ LoginPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
using System; using System.Web.Security; using System.Web.UI; namespace TestProject { /// <summary> /// 로그인 페이지 /// </summary> public partial class LoginPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion #region 로그인 버튼 클릭시 처리하기 - loginButton_Click(sender, e) /// <summary> /// 로그인 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void loginButton_Click(object sender, EventArgs e) { UserRepository repository = new UserRepository(); string userID = this.userIDTextBox.Text.Trim(); string password = this.passwordTextBox.Text.Trim(); if(repository.IsValidUser(userID, password)) { if(!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { FormsAuthentication.RedirectFromLoginPage(userID, false); } else { FormsAuthentication.SetAuthCookie(userID, false); Response.Redirect("~/WelcomePage.aspx"); } } else { Page.ClientScript.RegisterStartupScript ( this.GetType(), "loginButton_Click", "<script>alert('잘못된 사용자입니다.');</script>" ); } } #endregion } } |
▶ RegisterPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegisterPage.aspx.cs" Inherits="TestProject.RegisterPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>회원 관리</h1> <h2>회원 가입</h2> 아이디 : <asp:TextBox ID="userIDTextBox" runat="server" /><br /> 암호 : <asp:TextBox ID="passwordTextBox" runat="server" TextMode="Password" /> <br /> <asp:Button ID="registerButton" runat="server" Text="등록" OnClick="registerButton_Click" /> <br /> </div> </form> </body> </html> |
▶ RegisterPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 등록 페이지 /// </summary> public partial class RegisterPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion #region 등록 버튼 클릭시 처리하기 - registerButton_Click(sender, e) /// <summary> /// 등록 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void registerButton_Click(object sender, EventArgs e) { UserRepository repository = new UserRepository(); repository.AddUser(this.userIDTextBox.Text.Trim(), this.passwordTextBox.Text.Trim()); string script = "<script>alert('등록 완료');location.href='MainPage.aspx';</script>"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerTextBox_Click", script); } #endregion } } |
▶ LogoutPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LogoutPage.aspx.cs" Inherits="TestProject.LogoutPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> </div> </form> </body> </html> |
▶ LogoutPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Web.Security; using System.Web.UI; namespace TestProject { /// <summary> /// 로그아웃 페이지 /// </summary> public partial class LogoutPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect("~/MainPage.aspx"); } #endregion } } |
▶ WelcomePage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WelcomePage.aspx.cs" Inherits="TestProject.WelcomePage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>회원 관리</h1> <h2>로그인 확인</h2> <asp:Label ID="nameLabel" runat="server" /> 님, 반갑습니다. </div> </form> </body> </html> |
▶ WelcomePage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 환영 페이지 /// </summary> public partial class WelcomePage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(Page.User.Identity.IsAuthenticated) { this.nameLabel.Text = Page.User.Identity.Name; } else { Response.Redirect("~/LoginPage.aspx"); } } #endregion } } |
▶ UserPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPage.aspx.cs" Inherits="TestProject.UserPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>회원 관리</h1> <h2>회원 정보 보기</h2> ID : <asp:Label ID="idLabel" runat="server" /> <br /> 아이디 : <asp:TextBox ID="userIDTextBox" runat="server" /> <br /> 암호 : <asp:TextBox ID="passwordTextBox" runat="server" TextMode="Password" /> <br /> <asp:Button ID="updateButton" runat="server" Text="수정" OnClick="updateButton_Click" /> </div> </form> </body> </html> |
▶ UserPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
using System; using System.Web.UI; using TestProject.Models; namespace TestProject { /// <summary> /// 사용자 페이지 /// </summary> public partial class UserPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!Page.User.Identity.IsAuthenticated) { Response.Redirect("~/LoginPage.aspx"); } if(!Page.IsPostBack) { DisplayData(); } } #endregion #region 수정 버튼 클릭시 처리하기 - updateButton_Click(sender, e) /// <summary> /// 수정 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void updateButton_Click(object sender, EventArgs e) { UserRepository repository = new UserRepository(); repository.UpdateUser(Convert.ToInt32(this.idLabel.Text), this.userIDTextBox.Text.Trim(), this.passwordTextBox.Text.Trim()); string script = "<script>alert('수정 완료');location.href='MainPage.aspx';</script>"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "updateButton_Click", script); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 데이터 표시하기 - DisplayData() /// <summary> /// 데이터 표시하기 /// </summary> private void DisplayData() { UserRepository repository = new UserRepository(); UserModel user = repository.GetUser(Page.User.Identity.Name); this.idLabel.Text = user.ID.ToString(); this.userIDTextBox.Text = user.UserID; this.passwordTextBox.Text = user.Password; } #endregion } } |
▶ /Management/Web.config
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authorization> <allow users="user1, user2" /> <deny users="*" /> </authorization> </system.web> </configuration> |
▶ /Management/MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.Management.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormsAuthentication 클래스 : 사용자 로그인 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h1>관리자 전용 페이지</h1> <h2>관리자명 : <asp:LoginName ID="LoginName1" runat="server" /> </h2> </div> </form> </body> </html> |
▶ /Management/MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject.Management { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |