NuGet 패키지 관리자에서 다음 패키지를 설치한다.
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
using Microsoft.AspNetCore.Identity;
namespace MvcJqueryDemo.Models
{
public class ApplicationUser : IdentityUser
{
public string? DisplayName { get; set; }
}
}
이 모델은 Identity의 User를 상속받아서 자동으로 생성해준다 필드 내용은 이렇다
기존 ApplicationDbContext가 DbContext를 상속하고 있었지만 IdentityDbContext로 변경한다.
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MvcJqueryDemo.Models;
namespace MvcJqueryDemo.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<BoardModel> Boards { get; set; }
}
}
이제 Identity가 관리하는 회원 테이블들이 자동으로 생성된다.
기존 서비스 등록 부분에 Identity 설정을 추가한다.
// Identity 설정
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// 비밀번호 정책
options.Password.RequiredLength = 8;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
// 사용자 설정
options.User.RequireUniqueEmail = false;
// 로그인 실패 잠금
options.Lockout.AllowedForNewUsers = true;
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
DTOs/RegisterDto.cs
using System.ComponentModel.DataAnnotations;
namespace MvcJqueryDemo.Dtos
{
public class RegisterDto
{
[Required]
public string UserId { get; set; } = "";
[Required]
[MinLength(8)]
public string Password { get; set; } = "";
[Required]
public string UserName { get; set; } = "";
}
}
로그인 DTO도 만든다.
using System.ComponentModel.DataAnnotations;
namespace MvcJqueryDemo.Dtos
{
public class LoginDto
{
[Required]
public string UserId { get; set; } = "";
[Required]
public string Password { get; set; } = "";
}
}
이제 직접 비밀번호를 비교하지 않고 UserManager와 SignInManager 를 사용한다.
Controleers/AccountController.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MvcJqueryDemo.Dtos;
using MvcJqueryDemo.Models;
using MvcJqueryDemo.Services;
using System.Security.Claims;
namespace MvcJqueryDemo.Controllers
{
public class AccountController : Controller
{
private readonly IAccountService _accountService;
public AccountController(IAccountService accountService)
{
_accountService = accountService;
}
// 로그인 화면
[HttpGet]
public IActionResult Login()
{
return View();
}
// 로그인 처리
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromBody] LoginDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(new
{
success = false,
message = "아이디와 비밀번호를 입력하세요."
});
}
var result = await _accountService.LoginAsync(dto);
if (!result)
{
return Unauthorized(new
{
success = false,
message = "아이디 또는 비밀번호가 올바르지 않습니다."
});
}
return Ok(new
{
success = true,
message = "로그인되었습니다.",
redirectUrl = "/Board/Index"
});
}
// 회원가입 화면
[HttpGet]
public IActionResult Register()
{
return View();
}
// 회원가입 처리
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register([FromBody]RegisterDto dto)
{
var result = await _accountService.RegisterAsync(dto);
if (!result)
{
return BadRequest(new
{
success = false,
message = "회원가입에 실패했습니다."
});
}
return Ok(new
{
success = true,
message = "회원가입이 완료되었습니다."
});
}
// 로그아웃
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _accountService.LogoutAsync();
return Ok(new
{
success = true,
message = "로그아웃되었습니다.",
redirectUrl = "/Account/Login"
});
}
// 권한 없음
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
}
}
해당 매니저 로직은 서비스에 담아놓는다 컨트롤러는 서비스인터페이스를 상속받아와서 리턴값만 적어놓음
AccountService
using Microsoft.AspNetCore.Identity;
using MvcJqueryDemo.Dtos;
using MvcJqueryDemo.Models;
using MvcJqueryDemo.Repositories;
namespace MvcJqueryDemo.Services
{
public class AccountService : IAccountService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public AccountService(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
// 회원가입
public async Task<bool> RegisterAsync(RegisterDto dto)
{
var user = new ApplicationUser
{
UserName = dto.UserId,
DisplayName = dto.UserName
};
var result = await _userManager.CreateAsync(user, dto.Password);
return result.Succeeded;
}
// 로그인
public async Task<bool> LoginAsync(LoginDto dto)
{
var result = await _signInManager.PasswordSignInAsync(
dto.UserId,
dto.Password,
false,
true
);
return result.Succeeded;
}
public async Task LogoutAsync()
{
await _signInManager.SignOutAsync();
}
}
}
그리고 서비스는 인터페이스를 상속받음
IAccountService
using MvcJqueryDemo.Dtos;
using MvcJqueryDemo.Models;
namespace MvcJqueryDemo.Services
{
public interface IAccountService
{
Task<bool> RegisterAsync(RegisterDto dto);
Task<bool> LoginAsync(LoginDto dto);
Task LogoutAsync();
}
}
그리고 인터페이스서비스를 상속받으면 서비스를 불러올수 있게 Program.cs에 서비스 의존성을 등록해줌
// 서비스 등록(인터페이스를 불러오면 구현체가 실행됨)
builder.Services.AddScoped<IBoardService, BoardService>();
builder.Services.AddScoped<IAccountService, AccountService>();
로그인과 회원가입 화면은 AJAX 방식을 그대로 쓸 수 있다.
Login.cshtml
@{
ViewData["Title"] = "로그인";
}
<h2>로그인</h2>
<form id="loginForm">
@Html.AntiForgeryToken()
<div>
<input type="text" id="UserId" name="UserId" placeholder="아이디" />
</div>
<div>
<input type="password" id="Password" name="Password" placeholder="비밀번호" />
</div>
<button type="submit">로그인</button>
</form>
<script src="~/js/account.js"></script>
Register.cshtml
@{
ViewData["Title"] = "회원가입";
}
<h2>회원가입</h2>
<form id="registerForm">
@Html.AntiForgeryToken()
<div>
<input type="text"
id="UserId"
name="UserId"
placeholder="아이디" />
</div>
<div>
<input type="password"
id="Password"
name="Password"
placeholder="비밀번호" />
</div>
<div>
<input type="text"
id="UserName"
name="UserName"
placeholder="이름" />
</div>
<button type="submit">회원가입</button>
</form>
<script src="~/js/account.js"></script>
account.js
$(document).ready(function () {
$("#loginForm").on("submit", function (e) {
e.preventDefault();
const userData = {
UserId: $("#UserId").val(),
Password: $("#Password").val()
};
$.ajax({
url: "/Account/Login",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
headers: {
"RequestVerificationToken":
$('input[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(userData),
success: function (res) {
alert(res.message);
location.href = res.redirectUrl;
},
error: function (xhr) {
alert(xhr.responseJSON?.message
|| "로그인에 실패했습니다.");
}
});
});
$("#registerForm").on("submit", function (e) {
e.preventDefault();
const userData = {
UserId: $("#UserId").val(),
Password: $("#Password").val(),
UserName: $("#UserName").val()
};
$.ajax({
url: "/Account/Register",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"RequestVerificationToken":
$('input[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(userData),
success: function (res) {
alert(res.message);
location.href = res.redirectUrl;
},
error: function (xhr) {
console.log("상태 코드:", xhr.status);
console.log("응답 데이터:", xhr.responseJSON);
if (xhr.responseJSON?.errors) {
console.log("검증 오류:", xhr.responseJSON.errors);
alert(JSON.stringify(xhr.responseJSON.errors));
} else {
alert(xhr.responseJSON?.message || "회원가입 실패");
}
}
});
});
$("#btnLogout").on("click", function () {
$.ajax({
url: "/Account/Logout",
type: "POST",
headers: {
"RequestVerificationToken":
$('input[name="__RequestVerificationToken"]').val()
},
success: function (res) {
alert(res.message);
location.href = res.redirectUrl;
},
error: function (xhr) {
alert("로그아웃에 실패했습니다.");
}
});
});
});
Dto에 맞춰서 AJAX 요청을 보내면 된다.
Identity 테이블을 생성하자
패키지 관리자 콘솔에서 명령어를 실행하면 된다.
Add-Migration AddIdentity
Update-Database
Identity에서는 역할(Role)을 이용해 관리자와 일반 사용자를 구분할 수 있다.
예를 들어 게시판 관리자 기능을 다음처럼 제한할 수 있다.
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
일반 로그인 사용자만 접근하도록 하려면
[Authorize]
public class BoardController : Controller
{
public IActionResult Index()
{
return View();
}
}
[Authorize] 를 사용해주면 된다
역할은 RoleManager 로 Admin, User를 생성하고, 관리자가 승인한 사용자에게만 Admin 역할을 부여해야한다. 일반 회원가입 과정에서 관리자 역할을 부여하면 절대 안된다.