ASP.NET Core Blazor 인증 상태

참고 항목

이 문서의 최신 버전은 아닙니다. 현재 릴리스는 이 문서의 .NET 8 버전을 참조 하세요.

Warning

이 버전의 ASP.NET Core는 더 이상 지원되지 않습니다. 자세한 내용은 .NET 및 .NET Core 지원 정책을 참조 하세요. 현재 릴리스는 이 문서의 .NET 8 버전을 참조 하세요.

Important

이 정보는 상업적으로 출시되기 전에 실질적으로 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적, 또는 묵시적인 보증을 하지 않습니다.

현재 릴리스는 이 문서의 .NET 8 버전을 참조 하세요.

이 문서에서는 사용자 지정 인증 상태 공급자 를 만들고 코드에서 사용자 인증 상태 변경 알림을 받는 방법을 설명합니다.

서버 쪽 및 클라이언트 쪽 Blazor 앱에 대해 수행되는 일반적인 접근 방식은 유사하지만 정확한 구현은 다르므로 이 문서에서는 서버 쪽 앱과 클라이언트 쪽 Blazor Blazor 앱 간에 피벗합니다. 아티클 맨 위에 있는 피벗 선택기를 사용하여 작업 중인 프로젝트 유형 Blazor 과 일치하도록 아티클의 피벗을 변경합니다.

  • 서버 쪽 Blazor 앱(Server피벗): Blazor Server .NET 7 이하 및 .NET 8 이상의 서버 프로젝트 Blazor Web App
  • 클라이언트 쪽 Blazor 앱(Blazor WebAssembly 피벗): Blazor WebAssembly .NET의 모든 버전 또는 .Client .NET 8 이상용 프로젝트의 Blazor Web App 경우.

추상 AuthenticationStateProvider 클래스

프레임워크에는 Blazor 다음 멤버를 사용하여 현재 사용자의 인증 상태에 대한 정보를 제공하는 추상 AuthenticationStateProvider 클래스가 포함되어 있습니다.

  • GetAuthenticationStateAsync: 현재 사용자의 인증 상태를 비동기적으로 가져옵니다.
  • AuthenticationStateChanged: 인증 상태가 변경될 때 알림을 제공하는 이벤트입니다. 예를 들어 사용자가 앱에 로그인하거나 앱에서 로그아웃하는 경우 이 이벤트가 발생할 수 있습니다.
  • NotifyAuthenticationStateChanged: 인증 상태가 변경된 이벤트를 발생합니다.

사용자 지정 AuthenticationStateProvider를 구현합니다.

앱은 앱에 Microsoft.AspNetCore.Components.Authorization 대한 Blazor 인증 및 권한 부여 지원을 제공하는 NuGet 패키지를 참조해야 합니다.

참고 항목

.NET 앱에 패키지를 추가하는 방법에 대한 지침은 패키지 사용 워크플로에서 패키지 설치 및 관리의 문서(NuGet 설명서)를 참조하세요. NuGet.org에서 올바른 패키지 버전을 확인합니다.

파일에서 다음 인증, 권한 부여 및 연계 인증 상태 서비스를 구성합니다 Program .

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱은 인증 상태를 연계 매개 변수로 노출하는 것을 포함하여 다음 서비스 등록으로 미리 구성됩니다. 자세한 내용은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하고 구성 요소 섹션을 사용하여 권한 없는 콘텐츠 Router 사용자 지정 문서의 추가 정보를 참조하세요.

using Microsoft.AspNetCore.Components.Authorization;

...

builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();

파일에서 Program 인증 및 권한 부여 서비스를 구성합니다.

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱에는 다음 서비스 등록이 포함됩니다.

using Microsoft.AspNetCore.Components.Authorization;

...

builder.Services.AddAuthorization();

에서 인증 및 권한 부여 서비스를 구성합니다 Startup.ConfigureServices Startup.cs.

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱에는 다음 서비스 등록이 포함됩니다.

using Microsoft.AspNetCore.Components.Authorization;

...

services.AddAuthorization();

Blazor WebAssembly 앱(모든 .NET 버전) 또는 .Client (.NET 8 이상) 프로젝트에서 파일에서 Blazor Web App Program 인증, 권한 부여 및 연계 인증 상태 서비스를 구성합니다.

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱은 인증 상태를 연계 매개 변수로 노출하는 것을 포함하여 다음 서비스 등록으로 미리 구성됩니다. 자세한 내용은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하고 구성 요소 섹션을 사용하여 권한 없는 콘텐츠 Router 사용자 지정 문서의 추가 정보를 참조하세요.

using Microsoft.AspNetCore.Components.Authorization;

...

builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();

파일에서 Program 인증 및 권한 부여 서비스를 구성합니다.

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱에는 다음 서비스 등록이 포함됩니다.

using Microsoft.AspNetCore.Components.Authorization;

...

builder.Services.AddAuthorizationCore();

서브클래스 AuthenticationStateProvider 및 재정 GetAuthenticationStateAsync 의하여 사용자의 인증 상태를 만듭니다. 다음 예제에서는 모든 사용자가 사용자 이름으로 mrfibuli인증됩니다.

CustomAuthStateProvider.cs:

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

public class CustomAuthStateProvider : AuthenticationStateProvider
{
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var identity = new ClaimsIdentity(
        [
            new Claim(ClaimTypes.Name, "mrfibuli"),
        ], "Custom Authentication");

        var user = new ClaimsPrincipal(identity);

        return Task.FromResult(new AuthenticationState(user));
    }
}

참고 항목

ClaimsIdentity 코드를 만드는 이전 코드는 C# 12(.NET 8)에 도입된 간소화된 컬렉션 초기화를 사용합니다. 자세한 내용은 컬렉션 식 - C# 언어 참조를 참조하세요.

CustomAuthStateProvider 서비스가 파일에 등록됩니다Program. 다음으로 범위가 지정된 서비스를 등록합니다.AddScoped

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();

Blazor Server 앱에서 호출 후 범위가 지정된 AddScoped 서비스를 다음으로 등록합니다.AddServerSideBlazor

builder.Services.AddServerSideBlazor();

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();

Blazor Server 앱에서 호출 후 범위가 지정된 AddScoped 서비스를 다음으로 등록합니다.AddServerSideBlazor

services.AddServerSideBlazor();

services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();

CustomAuthStateProvider 서비스가 파일에 등록됩니다Program. 다음을 사용하여 서비스 싱글톤을 등록합니다.AddSingleton

builder.Services.AddSingleton<AuthenticationStateProvider, CustomAuthStateProvider>();

없는 경우 파일에 문을 _Imports.razor 추가하여 @using 구성 요소 간에 네임스페이 Microsoft.AspNetCore.Components.Authorization 스를 사용할 수 있도록 합니다.

@using Microsoft.AspNetCore.Components.Authorization;

경로 뷰 구성 요소를 구성 요소 정의의 구성 요소로 AuthorizeRouteView Router 확인하거나 변경합니다. 구성 요소의 Router 위치는 앱 유형에 따라 다릅니다. 프로젝트에서 해당 위치를 모르는 경우 검색을 사용하여 구성 요소를 찾습니다.

<Router ...>
    <Found ...>
        <AuthorizeRouteView RouteData="routeData" 
            DefaultLayout="typeof(Layout.MainLayout)" />
        ...
    </Found>
</Router>

참고 항목

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들면 앱에 AuthorizeRouteView 구성 요소가 포함됩니다. 자세한 내용은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하고 구성 요소 섹션을 사용하여 권한 없는 콘텐츠 Router 사용자 지정 문서의 추가 정보를 참조하세요.

Router 구성 요소가 있는 위치:

구성 요소의 Router 위치는 앱 유형에 따라 다릅니다. 프로젝트에서 해당 위치를 모르는 경우 검색을 사용하여 구성 요소를 찾습니다.

<CascadingAuthenticationState>
    <Router ...>
        <Found ...>
            <AuthorizeRouteView RouteData="routeData" 
                DefaultLayout="typeof(MainLayout)" />
            ...
        </Found>
    </Router>
</CascadingAuthenticationState>

참고 항목

인증을 Blazor 사용하도록 설정된 프로젝트 템플릿 중 Blazor 하나에서 앱을 만들 때 앱에는 해당 및 CascadingAuthenticationState 구성 요소가 포함 AuthorizeRouteView 됩니다. 자세한 내용은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하고 구성 요소 섹션을 사용하여 권한 없는 콘텐츠 Router 사용자 지정 문서의 추가 정보를 참조하세요.

다음 예제 AuthorizeView 구성 요소는 인증된 사용자의 이름을 보여 줍니다.

<AuthorizeView>
    <Authorized>
        <p>Hello, @context.User.Identity?.Name!</p>
    </Authorized>
    <NotAuthorized>
        <p>You're not authorized.</p>
    </NotAuthorized>
</AuthorizeView>

사용 AuthorizeView지침은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하세요.

인증 상태 변경 알림

사용자 지정 AuthenticationStateProvider기본 클래스에서 AuthenticationStateProvider 호출 NotifyAuthenticationStateChanged 하여 소비자에게 다시 렌더링할 인증 상태 변경을 알릴 수 있습니다.

다음 예제는 이 문서의 앞부분에 있는 사용자 지정 AuthenticationStateProvider 구현 섹션의 지침에 따라 사용자 지정 AuthenticationStateProvider 구현을 기반으로 합니다. 해당 섹션의 지침을 이미 따른 경우 다음은 CustomAuthStateProvider 섹션에 표시된 지침을 대체합니다.

다음 CustomAuthStateProvider 구현에서는 사용자 지정 메서드 AuthenticateUser를 노출하여 사용자를 로그인하고 소비자에게 인증 상태 변경을 알립니다.

CustomAuthStateProvider.cs:

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

public class CustomAuthStateProvider : AuthenticationStateProvider
{
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var identity = new ClaimsIdentity();
        var user = new ClaimsPrincipal(identity);

        return Task.FromResult(new AuthenticationState(user));
    }

    public void AuthenticateUser(string userIdentifier)
    {
        var identity = new ClaimsIdentity(
        [
            new Claim(ClaimTypes.Name, userIdentifier),
        ], "Custom Authentication");

        var user = new ClaimsPrincipal(identity);

        NotifyAuthenticationStateChanged(
            Task.FromResult(new AuthenticationState(user)));
    }
}

참고 항목

ClaimsIdentity 코드를 만드는 이전 코드는 C# 12(.NET 8)에 도입된 간소화된 컬렉션 초기화를 사용합니다. 자세한 내용은 컬렉션 식 - C# 언어 참조를 참조하세요.

구성 요소에서:

  • AuthenticationStateProvider를 삽입합니다.
  • 사용자의 식별자를 저장할 필드를 추가합니다.
  • 사용자 식별자를 사용하여 캐스팅 AuthenticationStateProvider 하고 호출 AuthenticateUser 하는 CustomAuthStateProvider 단추와 메서드를 추가합니다.
@inject AuthenticationStateProvider AuthenticationStateProvider

<input @bind="userIdentifier" />
<button @onclick="SignIn">Sign in</button>

<AuthorizeView>
    <Authorized>
        <p>Hello, @context.User.Identity?.Name!</p>
    </Authorized>
    <NotAuthorized>
        <p>You're not authorized.</p>
    </NotAuthorized>
</AuthorizeView>

@code {
    public string userIdentifier = string.Empty;

    private void SignIn()
    {
        ((CustomAuthStateProvider)AuthenticationStateProvider)
            .AuthenticateUser(userIdentifier);
    }
}

사용자 지정 서비스를 통해 인증 상태 변경에 대한 알림을 트리거하도록 앞의 접근 방식을 개선할 수 있습니다. 다음 CustomAuthenticationService 클래스는 인증 상태 공급자가 구독할 수 있는 이벤트()를 사용하여 백업 필드(currentUserUserChanged)에서 현재 사용자의 클레임 주체를 유지 관리합니다. 여기서 이벤트가 호출됩니다NotifyAuthenticationStateChanged. 이 섹션 CustomAuthenticationService 의 뒷부분에 추가 구성을 사용하여 이벤트를 트리거 UserChanged 하도록 설정하는 논리를 사용하여 구성 요소에 CurrentUser 삽입할 수 있습니다.

CustomAuthenticationService.cs:

using System.Security.Claims;

public class CustomAuthenticationService
{
    public event Action<ClaimsPrincipal>? UserChanged;
    private ClaimsPrincipal? currentUser;

    public ClaimsPrincipal CurrentUser
    {
        get { return currentUser ?? new(); }
        set
        {
            currentUser = value;

            if (UserChanged is not null)
            {
                UserChanged(currentUser);
            }
        }
    }
}

파일에서 Program 종속성 주입 컨테이너에 등록 CustomAuthenticationService 합니다.

builder.Services.AddScoped<CustomAuthenticationService>();

에서 Startup.ConfigureServices Startup.cs종속성 주입 컨테이너에 등록 CustomAuthenticationService 합니다.

services.AddScoped<CustomAuthenticationService>();

파일에서 Program 종속성 주입 컨테이너에 등록 CustomAuthenticationService 합니다.

builder.Services.AddSingleton<CustomAuthenticationService>();

다음은 CustomAuthStateProvider 이벤트를 구독합니다 CustomAuthenticationService.UserChanged . 메서드는 GetAuthenticationStateAsync 사용자의 인증 상태를 반환합니다. 처음에는 인증 상태가 .의 값을 기반으로 합니다 CustomAuthenticationService.CurrentUser. 사용자가 변경되면 호출에 대한 새 사용자(new AuthenticationState(newUser))에 대한 GetAuthenticationStateAsync새 인증 상태가 만들어집니다.

using Microsoft.AspNetCore.Components.Authorization;

public class CustomAuthStateProvider : AuthenticationStateProvider
{
    private AuthenticationState authenticationState;

    public CustomAuthStateProvider(CustomAuthenticationService service)
    {
        authenticationState = new AuthenticationState(service.CurrentUser);

        service.UserChanged += (newUser) =>
        {
            authenticationState = new AuthenticationState(newUser);
            NotifyAuthenticationStateChanged(Task.FromResult(authenticationState));
        };
    }

    public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
        Task.FromResult(authenticationState);
}

다음 구성 요소의 SignIn 메서드는 설정할 CustomAuthenticationService.CurrentUser사용자 식별자에 대한 클레임 보안 주체를 만듭니다.

@using System.Security.Claims
@inject CustomAuthenticationService AuthService

<input @bind="userIdentifier" />
<button @onclick="SignIn">Sign in</button>

<AuthorizeView>
    <Authorized>
        <p>Hello, @context.User.Identity?.Name!</p>
    </Authorized>
    <NotAuthorized>
        <p>You're not authorized.</p>
    </NotAuthorized>
</AuthorizeView>

@code {
    public string userIdentifier = string.Empty;

    private void SignIn()
    {
        var currentUser = AuthService.CurrentUser;

        var identity = new ClaimsIdentity(
            [
                new Claim(ClaimTypes.Name, userIdentifier),
            ],
            "Custom Authentication");

        var newUser = new ClaimsPrincipal(identity);

        AuthService.CurrentUser = newUser;
    }
}

참고 항목

ClaimsIdentity 코드를 만드는 이전 코드는 C# 12(.NET 8)에 도입된 간소화된 컬렉션 초기화를 사용합니다. 자세한 내용은 컬렉션 식 - C# 언어 참조를 참조하세요.

추가 리소스