'ASP.NET & Core를 다루는 기술'이라는 책을 통해서 ASP.NET 공부를 하기 시작했다. 공부를 하다보니 예제와 설명이 적절하게 섞여서 나온 책인 것 같다. 위의 책을 바탕으로 공부한 내용을 글로 쓰려한다.
2020/03/03 - [ASP.NET 공부] ASP.NET 로그인 컨트롤과 회원 관리 (1) - 짱우의 코딩일기 - 티스토리
전에 로그인 기능 중 회원가입 기능을 구현하는 글을 게시했었고 이번에는 로그인 한 이후에 웹페이지가 변하는 기능에 대해 글을 써보려 한다. 회원가입 기능을 만들면서 만들었던 메서드를 계속 사용하기 때문에 정확한 이해를 위해 위의 글을 한 번 살펴보는걸 추천한다.
로그인 웹 폼 만들기
프로젝트 루트에 'Login.aspx' 웹 폼을 생성하고 코드는 다음과 같이 입력한다.
/Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="DevUser.Login" %>
<!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>회원 관리 - 로그인</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>회원 관리</h1>
<h2>로그인</h2>
아이디 : <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox><br />
암호 : <asp:TextBox ID="txtPassword" runat="server" TextMode="Password""></asp:TextBox><br />
<asp:Button ID="btnLogin" runat="server" Text="로그인" OnClick="btnLogin_Click" />
</div>
</form>
</body>
</html>
/Login.aspx.cs
Repository 클래스에 미리 구현된 IsCorrectUser 메서드를 사용해서 아이디와 암호가 일치하면 인증 값을 부여하고, 그렇지 않으면 "없는 사용자입니다" 라는 메시지가 출력된다.
using DevUser.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DevUser
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
UserRepository userRepo = new UserRepository();
if (userRepo.IsCorrectUser(txtUserID.Text, txtPassword.Text))
{
// [!] 인증 부여
if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
// 인증 쿠키값 부여
FormsAuthentication.RedirectFromLoginPage(txtUserID.Text, false);
else
{
// 인증 쿠키값 부여
FormsAuthentication.SetAuthCookie(txtUserID.Text, false);
Response.Redirect("~/Welcome.aspx");
}
}
else
Page.ClientScript.RegisterStartupScript(this.GetType(), "showMsg", "<script>alert('잘못된 사용자입니다.');</script>");
}
}
}
로그아웃 기능
- 프로젝트 루트에 'Logout.aspx' 웹 폼을 생성하고 코드는 다음과 같이 입력한다.
- 다음 웹 폼은 따로 UI를 갖지 않는 페이지고 'Default.aspx' 페이지에서 로그아웃 링크를 클릭하면 인증값이 제거된 후 'Default.aspx'로 다시 이동한다.
/Logout.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// [!] 로그아웃
FormsAuthentication.SignOut();
Response.Redirect("~/Default.aspx");
}
로그인 후 화면
프로젝트 루트에 'Welcome.aspx' 웹 폼을 생성하고 코드는 다음과 같이 입력한다.
/Welcome.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Welcome.aspx.cs" Inherits="DevUser.Welcome" %>
<!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>회원 관리 - 로그인 확인</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>회원 관리</h1>
<h2>로그인 확인</h2>
<asp:Label ID="lblName" runat="server"></asp:Label>님, 반갑습니다.
</div>
</form>
</body>
</html>
/Welcome.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DevUser
{
public partial class Welcome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// [!] 인증 여부 확인 : 로그인했으면 참, 그렇지 않으면 거짓을 반환
if (Page.User.Identity.IsAuthenticated)
// [!] 인증 이름 출력
lblName.Text = Page.User.Identity.Name;
else
Response.Redirect("~/Login.aspx"); // 로그인 페이지로 이동
}
}
}
직접 Login 페이지 URL을 쳐서 들어오게 되면 로그인을 진행하고 나서 따로 ReturnUrl 쿼리 스트링이 제공되지 않는다. 이런 경우를 위해 Welcome 웹 폼을 생성해 준 것이다.
회원 정보 상세보기 페이지
프로젝트 루트에 'UserInfo.aspx' 웹 폼을 생성하고 코드는 다음과 같이 입력한다.
/UserInfo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserInfo.aspx.cs" Inherits="DevUser.UserInfo" %>
<!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>회원 관리 - 회원 정보 보기</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>회원 관리</h1>
<h2>회원 정보 보기</h2>
UID : <asp:Label ID="lblUID" runat="server"></asp:Label><br />
아이디 : <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox><br />
암호 : <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox><br />
<asp:Button ID="btnModify" runat="server" Text="정보 수정" OnClick="btnModify_Click" />
</div>
</form>
</body>
</html>
/UserInfo.aspx.cs
using DevUser.Models;
using DevUser.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DevUser
{
public partial class UserInfo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.User.Identity.IsAuthenticated)
Response.Redirect("~/Login.aspx");
if (!Page.IsPostBack)
DisplayData();
}
private void DisplayData()
{
UserRepository userRepo = new UserRepository();
UserViewModel model = userRepo.GetUserByUserID(Page.User.Identity.Name);
lblUID.Text = model.ID.ToString();
txtUserID.Text = model.userID;
txtPassword.Text = model.password;
}
protected void btnModify_Click(object sender, EventArgs e)
{
// 데이터 수정
UserRepository userRepo = new UserRepository();
userRepo.ModifyUser(Convert.ToInt32(lblUID.Text), txtUserID.Text, txtPassword.Text);
// 메시지 박스 출력 후 기본 페이지로 이동
string strJs = "<script>alert('수정완료'); location.href='Default.aspx';</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "goDefault", strJs);
}
}
}
'UserInfo.aspx' 페이지는 직접 호출해서 들어갈 수 없게 만들어놓았다. ( if 문을 통해서 인증 여부를 판단해서 로그인 되지 않은 상태면 로그인 페이지로 이동시키기 때문 )
관리자 페이지 만들기
프로젝트 루트에 Admin 디렉토리를 생성한다. 디렉토리 내에 'Web.config' 파일을 추가하고 다음과 같은 코드를 작성한다.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<!-- Admin 폴더는 RedPlus만 접근 가능 -->
<allow users="Admin, Red" />
<deny users="*"/>
</authorization>
</system.web>
</configuration>
Admin 디렉토리에 'Default.aspx' 웹 폼을 생성하고 코드는 다음과 같이 입력한다.
/Admin/Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DevUser.Admin.Default" %>
<!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>관리자 전용 페이지</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>관리자 전용 페이지</h1>
<h2>관리자명 : <asp:LoginName ID="LoginName1" runat="server" /></h2>
</div>
</form>
</body>
</html>
해당 페이지에 Admin 계정이 접속한 모습이다.
Admin 계정이 아닌 다른 계정으로 /Admin/Default.aspx 페이지로 들어가게 되면 위와 같은 페이지가 뜨게 된다.
'WEB > ASP.NET' 카테고리의 다른 글
[ASP.NET 공부] ASP.NET 4.6 MVC 프레임워크(2) - 짱우의 코딩일기 - 티스토리 (0) | 2020.03.26 |
---|---|
[ASP.NET 공부] ASP.NET 4.6 MVC 프레임워크(1) - 짱우의 코딩일기 - 티스토리 (0) | 2020.03.24 |
[ASP.NET 공부] ASP.NET 로그인 컨트롤과 회원 관리 (1) - 짱우의 코딩일기 - 티스토리 (0) | 2020.03.03 |
[ASP.NET 공부] Micro ORM인 Dapper 다루기 - 짱우의 코딩일기 - 티스토리 (0) | 2020.02.29 |
[ASP.NET 공부] ADO.NET 데이터베이스 프로그래밍 (CRUD) - 짱우의 코딩일기 - 티스토리 (0) | 2020.02.02 |