본문 바로가기
ASP.NET Core

ASP.NET Core MVC 6] Identity

by Fastlane 2022. 1. 12.
728x90
반응형

소스 : https://github.com/BigExecution/CoreMVC_Login

ASP.NET Core Identity는 로그인 기능을 지원하는 API이다. 

사용자, 암호, 프로필 데이터, 역할, 클레임, 토큰, 메일 확인 등을 관리한다. 

Facebook, Google, Microsoft, Twitter 같은 외부 로그인도 사용할 수 있다. 

ASP.NET Core Identity를 사용하기 위한 설정

1. IdentityDbContext class 상속받는 ApplicationDbContext 클래스 추가 

ApplicationDbContext class는 반드시 IdentityDbContext를 상속받아야 한다.

Nuget Package 설치 :

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore.Tools : DB Migration에 필요함

IdentityDbContext는 SQL Server의 identity table을 관리하는데 필요한 모든 DbSet properties를 가지고 있다. IdentityDbContext는 내부적으로 DbContext를 상속받고 있다. 

ApplicationDbContext.cs 파일 추가 

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Employee.Models
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Core Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Core Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

2. Identity service 추가

Program.cs

builder.Services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(
    builder.Configuration.GetConnectionString("DefaultConnection")
    ));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

3. app.UseAuthentication(); 추가 

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

4. Identity Tables 생성

PM> Add-Migration InitialCreate
PM> Update-Database
Build started...
Build succeeded.
......
Done.

DB에 테이블이 생성된 것을 확인할 수 있다. 

User : 사용자

Role : 역할

UserClaim : 사용자가 소유한 클레임

UserToken : 사용자의 인증토큰

UserLogin : 사용자를 로그인에 연결

RoleClaim : 역할 내의 모든 사용자에게 부여되는 클레임

UserRole : 사용자와 역할을 연력하는 join entity

 

Migration History도 확인이 가능하다. 

 

 

 

 

 

 

 

 

728x90
반응형

댓글