主要是前面四步,第五步是需要授权验证画面的书写参数。
1. 引用 Microsoft.AspNetCore.Components.Authorization
2. Program.cs 加入:
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddAuthorizationCore();//There is no registered service of type 'Microsoft.AspNetCore.Authorization.IAuthorizationPolicyProvider'
builder.Services.AddSingleton<AuthenticationStateProvider, MyAuthenticationStateProvider>();
3. MyAuthenticationStateProvider.cs 类
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading.Tasks;
namespace UserLocalLogin
{
public class MyAuthenticationStateProvider : AuthenticationStateProvider
{
public override async Task<AuthenticationState> GetAuthenticationStateAsync() => new AuthenticationState(await GetUser(useCache: true));
private async ValueTask<ClaimsPrincipal> GetUser(bool useCache = false)
{
var identity = new ClaimsIdentity("Cookie");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
identity.AddClaim(new Claim(ClaimTypes.Name,"wyz"));
return new ClaimsPrincipal(identity);
}
}
}
4. App.razor 修改为
@using Microsoft.AspNetCore.Components.Authorization
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
5. 效果 index.razor
@page "/"
@using Microsoft.AspNetCore.Components.Authorization;
@using System.Security.Claims;
@*@using BlazorWasmCookieAuth.Shared.Authorization;*@
@using BlazorWasmCookieAuth.Client.Services;
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<AuthorizeView>
<Authorized>
<strong>Hello, @context.User.Identity.Name !</strong>
</Authorized>
<NotAuthorized>
<div>未登录</div>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</NotAuthorized>
</AuthorizeView>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}