첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ FormsAuthentication 클래스 : 사용자 로그인 관리하기

------------------------------------------------------------------------------------------------------------------------


TestProject.zip


TestDB.sql

 

 

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

 

 

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

 

 

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

 

 

<?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

 

 

<%@ 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

 

 

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

 

 

<%@ 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

 

 

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

 

 

<%@ 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

 

 

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

 

 

<%@ 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

 

 

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

 

 

<%@ 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

 

 

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

 

 

<%@ 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

 

 

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

 

 

<?xml version="1.0" encoding="utf-8"?>

<configuration>

    <system.web>

        <authorization>

            <allow users="user1, user2" />

            <deny users="*" />

        </authorization>

    </system.web>

</configuration>

 

 

/Management/MainPage.aspx

 

 

<%@ 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

 

 

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

    }

}

 

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요