Blazor WebAssembly 自定义用户登录进行授权

主要是前面四步,第五步是需要授权验证画面的书写参数。

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++;
    }
 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值