보안 ASP.NET Core 서버 쪽 Blazor 앱

참고 항목

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

Important

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

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

이 문서에서는 ASP.NET Core 애플리케이션으로 서버 쪽 Blazor 앱을 보호하는 방법을 설명합니다.

서버 쪽 Blazor 앱은 ASP.NET Core 앱과 동일한 방식으로 보안을 위해 구성됩니다. 자세한 내용은 ASP.NET Core 보안 주제에 있는 문서를 참조하세요.

인증 컨텍스트는 앱이 시작될 때만 설정되며, 앱이 WebSocket에 처음 연결하는 경우입니다. 인증 컨텍스트는 회로의 수명 동안 기본. 앱은 기본적으로 현재 30분마다 사용자의 인증 상태를 주기적으로 다시 유효성을 검사합니다.

앱이 사용자 지정 서비스에 대한 사용자를 캡처하거나 사용자 업데이트에 반응해야 하는 경우 서버 쪽 ASP.NET Core Blazor 추가 보안 시나리오를 참조하세요.

Blazor 는 모든 페이지 탐색에서 s를 사용하여 새 HTTP 요청을 만드는 기존의 서버 렌더링 웹앱과 cookie다릅니다. 탐색 이벤트 중에 인증이 검사. 그러나 관련 cookie되지 않습니다. Cookies는 서버에 HTTP 요청을 할 때만 전송되며, 이는 사용자가 앱에서 Blazor 탐색할 때 수행되지 않습니다. 탐색하는 동안 사용자의 인증 상태는 회로 내에서 Blazor 검사 추상화RevalidatingAuthenticationStateProvider 서버에서 언제든지 업데이트할 수 있습니다.

Important

탐색 중에 인증 유효성 검사를 달성하기 위해 사용자 지정 NavigationManager 을 구현하는 것은 권장되지 않습니다. 앱이 탐색 중에 사용자 지정 인증 상태 논리를 실행해야 하는 경우 사용자 지정AuthenticationStateProvider사용합니다.

참고 항목

이 문서의 코드 예제에서는 NRT(nullable 참조 형식) 및 .NET 컴파일러 null 상태 정적 분석을 채택합니다. 이 분석은 .NET 6 이상의 ASP.NET Core에서 지원됩니다. ASP.NET Core 5.0 이하를 대상으로 하는 경우 이 문서의 예제에서 null 형식 지정(?)을 제거합니다.

프로젝트 템플릿

ASP.NET CoreBlazor용 도구의 지침에 따라 새 서버 쪽 Blazor 앱을 만듭니다.

서버 쪽 앱 템플릿을 선택하고 프로젝트를 구성한 후 인증 유형에서 앱의 인증을 선택합니다.

  • 없음 (기본값): 인증이 없습니다.
  • 개별 계정: 사용자 계정은 ASP.NET Core Identity를 사용하여 앱 내에 저장됩니다.
  • 없음 (기본값): 인증이 없습니다.
  • 개별 계정: 사용자 계정은 ASP.NET Core Identity를 사용하여 앱 내에 저장됩니다.
  • Microsoft ID 플랫폼: 자세한 내용은 ASP.NET Core Blazor 인증 및 권한 부여를 참조하세요.
  • Windows: Windows 인증을 사용합니다.

BlazorIdentity UI(개별 계정)

Blazor 는 개별 계정에 대한 인증 옵션을 선택할 때 전체 Blazor기반 Identity UI 생성을 지원합니다.

웹앱 템플릿은 Blazor SQL Server 데이터베이스에 대한 코드를 스캐폴드합니다 Identity . 명령줄 버전은 기본적으로 SQLite를 사용하며 에 대한 SQLite 데이터베이스를 Identity포함합니다.

템플릿은 다음을 처리합니다.

  • 사용자 로그인 및 로그아웃과 같은 일상적인 인증 작업에 대한 구성 요소 및 관련 논리를 추가 IdentityRazor 합니다.
    • Identity 또한 구성 요소는 타사 앱을 사용하는 계정 확인 및 암호 복구 및 다단계 인증같은 고급 Identity 기능도 지원합니다.
    • 대화형 SSR(대화형 서버 쪽 렌더링) 및 CSR(클라이언트 쪽 렌더링) 시나리오가 지원됩니다.
  • Identity관련 패키지 및 종속성을 추가합니다.
  • 에서 Identity 패키지를 참조합니다 _Imports.razor.
  • 사용자 지정 사용자 Identity 클래스(ApplicationUser)를 만듭니다.
  • 데이터베이스 컨텍스트(ApplicationDbContext)를 EF Core 만들고 등록합니다.
  • 기본 제공 Identity 엔드포인트에 대한 라우팅을 구성합니다.
  • 유효성 검사 및 비즈니스 논리를 포함합니다 Identity .

프레임워크의 Identity 구성 요소를 검사 Blazor 하려면 웹앱 프로젝트 템플릿(참조 원본)Account 폴더 및 Shared 폴더에 Blazor 액세스 Pages 합니다.

대화형 WebAssembly 또는 대화형 자동 렌더링 모드를 선택하면 서버는 모든 인증 및 권한 부여 요청을 처리하고 Identity 구성 요소는 Web App의 기본 프로젝트의 서버에 Blazor 정적으로 렌더링됩니다. 프로젝트 템플릿에는 서버와 브라우저 간에 사용자의 인증 상태를 동기화하는 클래스(참조 원본).Client 가 프로젝트에 포함됩니다PersistentAuthenticationStateProvider. 클래스는 .의 사용자 지정 구현입니다 AuthenticationStateProvider. 공급자는 클래스를 PersistentComponentState 사용하여 인증 상태를 미리 렌더링하고 페이지에 유지합니다.

BlazorIdentityDbContext 는 프로젝트 템플릿의 Identity 구성 요소가 대화형 작업을 지원하지 않고 정적으로 렌더링하기에 충분하기 때문에 DbContext 의도적인 팩터리에서 생성되지 않은 인스턴스에 따라 달라집니다.

웹앱의 Blazor 기본 프로젝트에서 인증 상태 공급자의 이름은 IdentityRevalidatingAuthenticationStateProvider (참조 원본)(서버 대화형 솔루션에만 해당) 또는 PersistingRevalidatingAuthenticationStateProvider (참조 원본)(WebAssembly 또는 자동 대화형 솔루션)입니다.

구성 요소에 정적 SSR을 적용하는 동시에 비 구성Identity 요소에 전역 대화형 렌더링 모드를 적용하는 방법에 대한 Identity 설명은 ASP.NET Core Blazor 렌더링 모드를 참조하세요.

미리 렌더링된 상태를 유지하는 방법에 대한 자세한 내용은 Prerender ASP.NET Core Razor 구성 요소를 참조하세요.

소셜 웹 사이트를 통해 외부 로그인을 통합하는 방법에 대한 UI 및 지침에 대한 자세한 내용은 BlazorIdentity .NET 8의 ID를 사용하는 새로운 기능을 참조하세요.

참고 항목

.NET 참조 원본의 설명서 링크는 일반적으로 다음 릴리스의 .NET을 위한 현재 개발을 나타내는 리포지토리의 기본 분기를 로드합니다. 특정 릴리스를 위한 태그를 선택하려면 Switch branches or tags(분기 또는 태그 전환) 드롭다운 목록을 사용합니다. 자세한 내용은 ASP.NET Core 소스 코드(dotnet/AspNetCore.Docs #26205)의 버전 태그를 선택하는 방법을 참조하세요.

Web Apps에서 Blazor 인증 상태 관리

이 섹션은 다음을 채택하는 Web Apps에 Blazor 적용됩니다.

  • 대화형 서버 쪽 렌더링(대화형 SSR) 및 CSR.
  • CSR(클라이언트 쪽 렌더링).

클라이언트 쪽 인증 상태 공급자는 내부에서 Blazor 만 사용되며 ASP.NET Core 인증 시스템과 통합되지 않습니다. 미리 렌더링하는 Blazor 동안 페이지에 정의된 메타데이터를 준수하고 ASP.NET Core 인증 시스템을 사용하여 사용자가 인증되었는지 확인합니다. 사용자가 한 페이지에서 다른 페이지로 이동하면 클라이언트 쪽 인증 공급자가 사용됩니다. 사용자가 페이지를 새로 고치면(전체 페이지 다시 로드) 클라이언트 쪽 인증 상태 공급자는 서버의 인증 결정에 관여하지 않습니다. 사용자의 상태는 서버에 의해 유지되지 않으므로 클라이언트 쪽에 기본 인증 상태가 손실됩니다.

이 문제를 해결하기 위해 가장 좋은 방법은 ASP.NET Core 인증 시스템 내에서 인증을 수행하는 것입니다. 클라이언트 쪽 인증 상태 공급자는 사용자의 인증 상태를 반영하기만 합니다. 인증 상태 공급자를 사용하여 이 작업을 수행하는 방법에 대한 예제는 웹앱 프로젝트 템플릿에서 Blazor 보여 줍니다.

  • PersistingRevalidatingAuthenticationStateProvider(참조 원본): 대화형 서버 쪽 렌더링(대화형 SSR) 및 클라이언트 쪽 렌더링(CSR)을 채택하는 Web Apps의 경우 Blazor 대화형 회로가 연결된 30분마다 연결된 사용자에 대한 보안 스탬프의 유효성을 다시 검사하는 서버 쪽 AuthenticationStateProvider 입니다. 또한 영구 구성 요소 상태 서비스를 사용하여 인증 상태를 클라이언트로 전달한 다음, CSR의 수명 동안 고정됩니다.

  • PersistingServerAuthenticationStateProvider(참조 원본): CSR만 채택하는 Web Apps의 경우 Blazor 이 서버 쪽 AuthenticationStateProvider 은 영구 구성 요소 상태 서비스를 사용하여 인증 상태를 클라이언트로 전달한 다음, CSR의 수명 동안 수정됩니다.

  • PersistentAuthenticationStateProvider(참조 원본): CSR을 채택하는 Web Apps의 경우 Blazor 서버에서 렌더링될 때 페이지에 유지되는 데이터를 찾아 사용자의 인증 상태를 결정하는 클라이언트 쪽 AuthenticationStateProvider 입니다. 이 인증 상태는 CSR의 수명 동안 고정됩니다. 사용자가 로그인하거나 로그아웃해야 하는 경우 전체 페이지 다시 로드가 필요합니다. 표시를 위해 사용자 이름 및 전자 메일만 제공합니다. 후속 요청을 할 때 서버에 인증하는 토큰은 포함되지 않습니다. 이 토큰은 서버에 대한 HttpClient 요청에 포함된 토큰을 cookie 사용하여 별도로 처리됩니다.

참고 항목

.NET 참조 원본의 설명서 링크는 일반적으로 다음 릴리스의 .NET을 위한 현재 개발을 나타내는 리포지토리의 기본 분기를 로드합니다. 특정 릴리스를 위한 태그를 선택하려면 Switch branches or tags(분기 또는 태그 전환) 드롭다운 목록을 사용합니다. 자세한 내용은 ASP.NET Core 소스 코드(dotnet/AspNetCore.Docs #26205)의 버전 태그를 선택하는 방법을 참조하세요.

스캐폴드 Identity

서버 쪽 Blazor 앱으로 스캐폴딩하는 Identity 방법에 대한 자세한 내용은 ASP.NET Core 프로젝트의 스캐폴드를 Identity 참조하세요.

서버 쪽 Blazor 앱으로 스캐폴드Identity:

외부 공급자의 추가 클레임 및 토큰

외부 공급자의 추가 클레임을 저장하려면 ASP.NET Core에서 외부 공급자의 추가 클레임 및 토큰 유지를 참조하세요.

Identity Server를 사용한 Azure App Service on Linux

Identity Server를 사용하여 Azure App Service on Linux에 배포할 때 발급자를 명시적으로 지정합니다. 자세한 내용은 SPA에 대한 Web API 백 엔드 보안을 위한 사용을 Identity 참조하세요.

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

앱에 사용자 지정 공급자가 필요한 경우 구현 AuthenticationStateProvider 하고 재정 GetAuthenticationStateAsync의합니다.

다음 예제에서는 모든 사용자가 사용자 이름으로 mrfibuli인증됩니다.

CustomAuthStateProvider.cs:

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

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

        var user = new ClaimsPrincipal(identity);

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

CustomAuthStateProvider 서비스는 파일에 등록됩니다.Program

using Microsoft.AspNetCore.Components.Authorization;

...

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

서비스는 CustomAuthStateProvider 다음을 호출한 Program 파일에 등록됩니다AddServerSideBlazor.

using Microsoft.AspNetCore.Components.Authorization;

...

builder.Services.AddServerSideBlazor();

...

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

서비스는 CustomAuthStateProvider 다음을 호출한 후에 등록됩니다Startup.ConfigureServicesStartup.csAddServerSideBlazor.

using Microsoft.AspNetCore.Components.Authorization;

...

services.AddServerSideBlazor();

...

services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();

구성 요소를 확인하거나 추가 AuthorizeRouteView 합니다 Router .

Routes 구성 요소(Components/Routes.razor)에서:

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

파일의 서비스 컬렉션 Program 에 연계 인증 상태 서비스를 추가합니다.

builder.Services.AddCascadingAuthenticationState();

참고 항목

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

구성 요소를 확인하거나 구성 요소에 추가 AuthorizeRouteViewCascadingAuthenticationState 합니다.Router

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

참고 항목

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

모든 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 구현에서는 사용자 지정 메서드 AuthenticateUser를 노출하여 사용자를 로그인하고 소비자에게 인증 상태 변경을 알립니다.

CustomAuthStateProvider.cs:

using System.Security.Claims;
using System.Threading.Tasks;
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[]
        {
            new Claim(ClaimTypes.Name, userIdentifier),
        }, "Custom Authentication");

        var user = new ClaimsPrincipal(identity);

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

구성 요소에서:

  • 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);
    }
}
@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);
    }
}

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

using System.Security.Claims;

public class AuthenticationService
{
    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 종속성 주입 컨테이너에 등록 AuthenticationService 합니다.

builder.Services.AddScoped<AuthenticationService>();

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

services.AddScoped<AuthenticationService>();

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

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

public class CustomAuthStateProvider : AuthenticationStateProvider
{
    private AuthenticationState authenticationState;

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

        service.UserChanged += (newUser) =>
        {
            authenticationState = new AuthenticationState(newUser);

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

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

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

@inject AuthenticationService AuthenticationService

<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 = AuthenticationService.CurrentUser;

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

        var newUser = new ClaimsPrincipal(identity);

        AuthenticationService.CurrentUser = newUser;
    }
}
@inject AuthenticationService AuthenticationService

<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 = AuthenticationService.CurrentUser;

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

        var newUser = new ClaimsPrincipal(identity);

        AuthenticationService.CurrentUser = newUser;
    }
}

AuthenticationStateProvider 구성 요소로 범위가 지정된 서비스에 삽입

사용자 지정 범위 내에서 해결 AuthenticationStateProvider 하려고 시도하지 마세요. 그러면 올바르게 초기화되지 않은 새 인스턴스 AuthenticationStateProvider 가 생성되기 때문입니다.

구성 요소로 범위가 지정된 서비스 내에서 액세스 AuthenticationStateProvider 하려면 지시문 또는 [Inject] 특성을 삽입 AuthenticationStateProvider@inject 하고 매개 변수로 서비스에 전달합니다. 이 방법을 사용하면 각 사용자 앱 인스턴스에 대해 올바른 초기화된 인스턴스 AuthenticationStateProvider 가 사용됩니다.

ExampleService.cs:

public class ExampleService
{
    public async Task<string> ExampleMethod(AuthenticationStateProvider authStateProvider)
    {
        var authState = await authStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity is not null && user.Identity.IsAuthenticated)
        {
            return $"{user.Identity.Name} is authenticated.";
        }
        else
        {
            return "The user is NOT authenticated.";
        }
    }
}

서비스를 범위로 등록합니다. 서버 쪽 Blazor 앱에서 범위가 지정된 서비스는 클라이언트 연결 회로의 기간과 동일한 수명을 갖습니다.

Program 파일에서:

builder.Services.AddScoped<ExampleService>();

Startup.csStartup.ConfigureServices에서 다음을 수행합니다.

services.AddScoped<ExampleService>();

다음은 InjectAuthStateProvider 구성 요소에 대한 설명입니다.

InjectAuthStateProvider.razor:

@page "/inject-auth-state-provider"
@inherits OwningComponentBase
@inject AuthenticationStateProvider AuthenticationStateProvider

<h1>Inject <code>AuthenticationStateProvider</code> Example</h1>

<p>@message</p>

@code {
    private string? message;
    private ExampleService? ExampleService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ExampleService = ScopedServices.GetRequiredService<ExampleService>();

        message = await ExampleService.ExampleMethod(AuthenticationStateProvider);
    }
}
@page "/inject-auth-state-provider"
@inject AuthenticationStateProvider AuthenticationStateProvider
@inherits OwningComponentBase

<h1>Inject <code>AuthenticationStateProvider</code> Example</h1>

<p>@message</p>

@code {
    private string? message;
    private ExampleService? ExampleService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ExampleService = ScopedServices.GetRequiredService<ExampleService>();

        message = await ExampleService.ExampleMethod(AuthenticationStateProvider);
    }
}

자세한 내용은 ASP.NET Core Blazor 종속성 주입에 대한 OwningComponentBase지침을 참조하세요.

사용자 지정으로 미리 렌더링하는 동안 권한이 없는 콘텐츠 표시 AuthenticationStateProvider

사용자 지정으로 미리 렌더링하는 동안 구성 요소AuthorizeView콘텐츠와 같이 권한이 없는 콘텐츠가 표시되지 않도록 하려면 다음 방법 중 하나를 채택합니다.AuthenticationStateProvider

  • 미리 렌더링 사용 안 함: 루트 구성 요소가 아닌 앱의 구성 요소 계층 구조에서 가장 높은 수준의 구성 요소로 설정된 false 매개 변수가 있는 렌더링 모드 prerender 를 나타냅니다.

    참고 항목

    구성 요소와 같은 루트 구성 요소를 대화형으로 App 만드는 것은 지원되지 않습니다. 따라서 미리 렌더링은 구성 요소에서 App 직접 사용하지 않도록 설정할 수 없습니다.

    웹앱 프로젝트 템플릿을 기반으로 하는 앱의 Blazor 경우 일반적으로 구성 요소(Components/App.razor)에서 구성 요소가 사용되는 경우 Routes 미리 렌더링을 App 사용하지 않도록 설정됩니다.

    <Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    

    또한 구성 요소에 대한 사전 렌더링을 HeadOutlet 사용하지 않도록 설정합니다.

    <HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    

    구성 요소 인스턴스에 적용된 렌더링 모드를 세밀하게 제어하여 미리 렌더링을 Routes 선택적으로 사용하지 않도록 설정할 수도 있습니다. 자세한 내용은 ASP.NET Core Blazor 렌더링 모드를 참조하세요.

  • 미리 렌더링 사용 안 함: 파일을 열고 _Host.cshtml 구성 요소 태그 도우미특성을 다음으로 Server변경 render-mode 합니다.

    <component type="typeof(App)" render-mode="Server" />
    
  • 앱이 시작되기 전에 서버에서 사용자 인증: 이 방법을 채택하려면 앱이 -based 로그인 페이지 또는 뷰를 Identity사용하여 사용자의 초기 요청에 응답하고 인증될 때까지 엔드포인트에 Blazor 대한 요청을 방지해야 합니다. 자세한 내용은 권한 부여로 보호되는 사용자 데이터를 사용하여 ASP.NET Core 앱 만들기를 참조하세요. 인증 후 미리 렌더링된 Razor 구성 요소의 권한 없는 콘텐츠는 사용자가 콘텐츠를 볼 수 있는 권한이 없는 경우에만 표시됩니다.

사용자 상태 관리

이름 AuthenticationStateProvider 에 "state"라는 단어에도 불구하고 일반 사용자 상태를 저장하기 위한 것이 아닙니다. AuthenticationStateProvider 은 앱에 로그인했는지 여부와 로그인한 사용자 등 앱에 대한 사용자의 인증 상태만 나타냅니다.

인증은 Pages 및 MVC 앱과 동일한 ASP.NET Core Identity 인증 Razor 을 사용합니다. ASP.NET Core Identity 에 대해 저장된 사용자 상태는 앱에 Blazor 코드를 추가하지 않고 흐릅니다. ASP.NET Core Identity 문서 및 자습서의 Identity 지침에 따라 앱 부분에서 기능을 적용 Blazor 합니다.

ASP.NET Core Identity외부의 일반 상태 관리에 대한 지침은 ASP.NET Core Blazor 상태 관리를 참조하세요.

추가 보안 추상화

인증 상태 관리에는 두 가지 추가 추상화가 참여합니다.

참고 항목

.NET 참조 원본의 설명서 링크는 일반적으로 다음 릴리스의 .NET을 위한 현재 개발을 나타내는 리포지토리의 기본 분기를 로드합니다. 특정 릴리스를 위한 태그를 선택하려면 Switch branches or tags(분기 또는 태그 전환) 드롭다운 목록을 사용합니다. 자세한 내용은 ASP.NET Core 소스 코드(dotnet/AspNetCore.Docs #26205)의 버전 태그를 선택하는 방법을 참조하세요.

임시 리디렉션 URL 유효 기간

이 섹션은 Web Apps에 Blazor 적용됩니다.

RazorComponentsServiceOptions.TemporaryRedirectionUrlValidityDuration 옵션을 사용하여 서버 쪽 렌더링에서 내보내 Blazor 는 임시 리디렉션 URL에 대한 데이터 보호 유효성의 수명을 얻거나 설정합니다. 이는 일시적으로만 사용되므로 클라이언트가 URL을 수신하고 탐색을 시작할 수 있을 만큼 수명만 길어야 합니다. 그러나 서버 간에 클록 기울이기를 허용할 만큼 길어야 합니다. 기본값은 5분입니다.

다음 예제에서는 값이 7분으로 확장됩니다.

builder.Services.AddRazorComponents(options => 
    options.TemporaryRedirectionUrlValidityDuration = 
        TimeSpan.FromMinutes(7));

추가 리소스