主要是前面四步,第五步是需要授权验证画面的书写参数。
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 修改为文章来源:https://www.toymoban.com/news/detail-860638.html
@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文章来源地址https://www.toymoban.com/news/detail-860638.html
@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++;
}
}
到了这里,关于Blazor WebAssembly 自定义用户登录进行授权的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!