개요
이전 글에서는 스캐폴딩을 사용하여 Identity 프로젝트를 자동 생성하는 방법을 다루었습니다. 이번에는 Identity를 수동으로 구성하고, 기본 클래스들을 확장하여 커스텀 속성을 추가하는 방법을 설명하겠습니다.
NuGet 패키지 설치
먼저 필요한 NuGet 패키지들을 프로젝트에 설치합니다. 다음 패키지들이 필수적입니다:
- Microsoft.AspNetCore.Identity.EntityFrameworkCore
- Pomelo.EntityFrameworkCore.MySql
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Design
커스텀 DbContext 클래스 생성
IdentityDbContext를 상속하여 데이터베이스 컨텍스트를 생성합니다:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace CustomIdentity.Data
{
public class CustomDbContext : IdentityDbContext
{
public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options)
{
}
}
}
연결 문자열 설정
appsettings.json 파일에 데이터베이스 연결 정보를 추가합니다:
{
"ConnectionStrings": {
"MainConnection": "Server=localhost;Port=3306;Database=CustomIdentityDB;User=admin;Password=password123"
}
}
Program.cs에서 의존성 주입 구성
애플리케이션 시작 시 Identity와 데이터베이스를 구성합니다:
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("MainConnection");
builder.Services.AddDbContext<CustomDbContext>(options =>
{
options.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 30)));
});
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<CustomDbContext>();
마이그레이션 생성 및 적용
패키지 관리자 콘솔에서 다음 명령어를 순차적으로 실행합니다:
Add-Migration InitialCreate -OutputDir Data/Migrations -Context CustomDbContext
Update-Database -Context CustomDbContext
데이터베이스가 성공적으로 생성되면 Identity에서 제공하는 기본 테이블들이 생성됩니다.
IdentityUser와 IdentityRole 확장하기
기본 클래스의 속성만으로는 실제 비즈니스 요건을 충족하기 어려운 경우가 많습니다. 커스텀 속성을 추가하여 사용자 및 역할 정보를 확장할 수 있습니다.
확장 사용자 클래스 생성
using Microsoft.AspNetCore.Identity;
namespace CustomIdentity.Data.Entities
{
public class AppUser : IdentityUser
{
public string Department { get; set; }
public DateTime? BirthDate { get; set; }
public bool IsActive { get; set; }
}
}
확장 역할 클래스 생성
using Microsoft.AspNetCore.Identity;
namespace CustomIdentity.Data.Entities
{
public class AppRole : IdentityRole
{
public string Description { get; set; }
public int Priority { get; set; }
}
}
DbContext 수정
확장된 클래스를 사용하도록 DbContext를 업데이트합니다:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using CustomIdentity.Data.Entities;
namespace CustomIdentity.Data
{
public class CustomDbContext : IdentityDbContext<AppUser, AppRole, string>
{
public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options)
{
}
}
}
서비스 등록 업데이트
Program.cs에서 확장된 클래스를 사용하도록 수정합니다:
builder.Services.AddIdentity<AppUser, AppRole>()
.AddEntityFrameworkStores<CustomDbContext>()
.AddDefaultTokenProviders();
마이그레이션 재실행
변경 사항을 반영하기 위해 새로운 마이그레이션을 생성하고 데이터베이스를 업데이트합니다:
Add-Migration AddCustomUserRoleFields -Context CustomDbContext
Update-Database -Context CustomDbContext
결과 확인
데이터베이스를 확인하면 Users와 Roles 테이블에 새로 추가한 필드들이 반영되어 있습니다. 이제 커스텀 속성을 활용하여 실제 비즈니스 로직을 구현할 수 있습니다.