首页 > 其他分享 >Blazor HyBrid 授权讲解

Blazor HyBrid 授权讲解

时间:2023-05-31 15:35:14浏览次数:51  
标签:HyBrid 授权 Components 讲解 using Blazor AuthenticationStateProvider Microsoft

Blazor HyBrid 授权讲解

本文介绍 ASP.NET Core 对 Blazor Hybrid 应用中的安全配置和管理及 ASP.NET Core Identity 的支持。

Blazor Hybrid 应用中的身份验证由本机平台库处理,因为后者提供了浏览器沙盒无法给予的经过增强的安全保证。 本机应用的身份验证使用特定于操作系统的机制或通过联合协议,如 OpenID Connect (OIDC)。 按照针对应用选择的标识提供者指南进行操作,然后使用本文中的指南进一步集成标识与 Blazor。

集成身份验证必须为 Razor 组件和服务实现以下目标:

准备工作

  • 安装Masa Blazor的模板,如果已经安装则忽略
dotnet new install Masa.Template::1.0.0-rc.2
  • 创建项目Photino项目模板
    image.png

  • 添加Microsoft.AspNetCore.Components.Authorization NuGet包到项目文件中

    <PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="7.0.5" />
    

自定义AuthenticationStateProvider处理程序

创建CustomAuthenticationStateProvider然后继承AuthenticationStateProvider

CustomAuthenticationStateProvider.cs代码文件

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

namespace MasaBlazorApp1;

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    private ClaimsPrincipal User { get; set; }

    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        if (User != null)
        {
            return Task.FromResult(new AuthenticationState(User));
        }
        var identity = new ClaimsIdentity();
        User = new ClaimsPrincipal(identity);

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

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

        User = new ClaimsPrincipal(identity);

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

在继承AuthenticationStateProvider方法会要重写GetAuthenticationStateAsync方法,用于给授权组件获取授权信息,

在这个代码当中的User是用于存储持久化我们的用户信息的如果需要对于授权修改,我们只需要修改这个自定义的处理程序即可。然后我们在CustomAuthenticationStateProvider中还自定义了AuthenticateUser这个是根据实际需求去实现,在目前这个代码中我们实现了个简单的Name在最后有一个NotifyAuthenticationStateChanged的调用,NotifyAuthenticationStateChanged是干啥的?NotifyAuthenticationStateChanged也是AuthenticationStateProvider提供的方法,核心功能是用于通知我们的授权状态被修改。

打开Program.cs然后注入我们的CustomAuthenticationStateProvider服务,在添加注入CustomAuthenticationStateProvider之前我们实现添加注入了AddAuthorizationCore,这个需要注意。

using MasaBlazorApp1;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Photino.Blazor;

internal class Program
{
    [STAThread]
    private static void Main(string[] args)
    {
        var builder = PhotinoBlazorAppBuilder.CreateDefault(args);

        builder.RootComponents.Add<App>("#app");
        builder.Services.AddMasaBlazor();

        builder.Services.AddAuthorizationCore();
        builder.Services.TryAddSingleton<AuthenticationStateProvider, CustomAuthenticationStateProvider>();

        var app = builder.Build();

        app.MainWindow
            .SetTitle("Photino Blazor Sample");

        AppDomain.CurrentDomain.UnhandledException += (sender, error) =>
        {
        };

        app.Run();
    }
}

然后继续打开我们的App.razor添加授权相关组件,修改之前在_Imports.razor添加以下引用

@using Microsoft.AspNetCore.Components.Authorization

添加未授权时显示的组件Shared/Login.razor,组件提供了一个输入框和一个按钮,输入框输入用户名,按钮则使用我们自定义的CustomAuthenticationStateProvider中提供的AuthenticateUser方法,用于更新授权信息从而刷新到授权的组件当中。

@inject AuthenticationStateProvider AuthenticationStateProvider

<MTextField @bind-Value="_userName" />

<MButton @onclick="SignIn">登录</MButton>

@code {
    private string _userName = "账号";

    private void SignIn()
    {
        ((CustomAuthenticationStateProvider)AuthenticationStateProvider)
            .AuthenticateUser(_userName);
    }
}

App.razor文件

@namespace MasaBlazorApp1

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeView>
                <Authorized>
                    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    </RouteView>
                </Authorized>
                <NotAuthorized>
                    <Login/>
                </NotAuthorized>
            </AuthorizeView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1"/>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

App.razor文件在Router中添加了AuthorizeView组件,用于显示授权显示的组件和未授权显示的组件。当有授权的情况下我们将使用默认的MainLayout布局,如果是未授权我们将实现Login,需要注意的是我们在组件最外层添加了CascadingAuthenticationState这个是核心组件,

CascadingAuthenticationState.cs 的反编译以后的代码,在组件当中注入了AuthenticationStateProvider然后在进入OnInitialized事件的时候对于AuthenticationStateProvider提供的AuthenticationStateChanged事件进行了监听,这个也就对应到了上面提到的NotifyAuthenticationStateChanged,当调用到NotifyAuthenticationStateChanged的时候会触发到AuthenticationStateChanged的事件,然后会触发组件的OnAuthenticationStateChanged方法,进行授权状态更新,这个也就是核心的组件。

    #line hidden
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Components;
    public partial class CascadingAuthenticationState : global::Microsoft.AspNetCore.Components.ComponentBase, IDisposable
    {
        #pragma warning disable 1998
        protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
            __builder.OpenComponent<global::Microsoft.AspNetCore.Components.CascadingValue<System.Threading.Tasks.Task<AuthenticationState>>>(0);
            __builder.AddAttribute(1, "Value", global::Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Threading.Tasks.Task<AuthenticationState>>(
#nullable restore
#line 4 "D:\a\_work\1\s\src\Components\Authorization\src\CascadingAuthenticationState.razor"
                                                                                  _currentAuthenticationStateTask

#line default
#line hidden
#nullable disable
            ));
            __builder.AddAttribute(2, "ChildContent", (global::Microsoft.AspNetCore.Components.RenderFragment)(
#nullable restore
#line 4 "D:\a\_work\1\s\src\Components\Authorization\src\CascadingAuthenticationState.razor"
                                                                                                                                  ChildContent

#line default
#line hidden
#nullable disable
            ));
            __builder.CloseComponent();
        }
        #pragma warning restore 1998
#nullable restore
#line 6 "D:\a\_work\1\s\src\Components\Authorization\src\CascadingAuthenticationState.razor"
       
    private Task<AuthenticationState>? _currentAuthenticationStateTask;

    /// <summary>
    /// The content to which the authentication state should be provided.
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    protected override void OnInitialized()
    {
        AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;

        _currentAuthenticationStateTask = AuthenticationStateProvider
            .GetAuthenticationStateAsync();
    }

    private void OnAuthenticationStateChanged(Task<AuthenticationState> newAuthStateTask)
    {
        _ = InvokeAsync(() =>
        {
            _currentAuthenticationStateTask = newAuthStateTask;
            StateHasChanged();
        });
    }

    void IDisposable.Dispose()
    {
        AuthenticationStateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
    }

#line default
#line hidden
#nullable disable
        [global::Microsoft.AspNetCore.Components.InjectAttribute] private AuthenticationStateProvider AuthenticationStateProvider { get; set; }
    }
}

效果

启动项目查看具体效果

image.png

默认进入登录界面,由于我们并没有授权信息,所以进入这个界面,然后我们随便输入一些内容点击登录。
screenshots.gif
当我们点击了登录按钮以后我们就进入到了MainLayout当中并且进入了首页。

对于授权Blazor由于模式都有所差异。

授权文档:ASP.NET Core Blazor Hybrid 身份验证和授权

结尾

来着token的分享

Blazor交流群:452761192

标签:HyBrid,授权,Components,讲解,using,Blazor,AuthenticationStateProvider,Microsoft
From: https://www.cnblogs.com/hejiale010426/p/17446232.html

相关文章

  • git pull 和push讲解:016
    pull和push大致流程:(将远程仓库同步到本地仓库)>(在本地仓库修改并提交)>(推送修改内容到远程仓库) 1.首先创建一个文件夹,打开GitBash终端,cd到这个文件夹内 2.将(远程仓库)的克隆到这个文件夹内:gitclone远程仓库连接 3.打开终端,然后cd进入项目文件 4.然后建立与(......
  • Blazor 跨平台的、共享一套UI的天气预报 Demo
    1.前言很久之前就读过dotnet9大佬的一篇文章,MAUI与Blazor共享一套UI,媲美Flutter,实现Windows、macOS、Android、iOS、Web通用UI,没读过的可以读一读,写的很好。对Blazor跨平台开始比较感兴趣。渐渐发现BlazorHybrid可以在更多的框架上运行,如Winform、WPF,更有Photino这样可以在......
  • Spring之状态机讲解
    目录1状态机1.1什么是状态1.2四大概念1.3状态机1.4springstatemachine2示例Demo2.1订单状态图2.2建表2.3依赖和配置2.3.1pom.xml2.3.2application.yml2.4状态机配置2.4.1定义状态机状态和事件2.4.2定义状态机规则2.4.3配置持久化2.4.3.1持久化到内存2.4.3.2持久......
  • 保姆级讲解,让ChatGPT成为机器人的智慧大脑
    ChatGPT是生成式人工智能,如果能接入机器人,可以让机器人更加智能。 我手上没有硬件,但我们可以模拟尝试机器人的制作逻辑,这个设计分成两部分:硬件、软件。 一、硬件:机器人 1.机器人可以听取人类的对话 2.机器人要接入ChatGPT 3.机器人可以根据ChatGPT的指示做出响......
  • 【2023 · CANN训练营第一季】应用开发深入讲解之AIPP
    应用开发深入讲解之AIPPAIPP(ArtificialIntelligencePre-Processing)人工智能预处理,在AlCore上完成数据预处理。动态&静态AIPP分为静态AIPP和动态AIPP两种,对比如下:2.抠图&填充AIPP改变图片尺寸需要遵守如下图中的顺序,即先Crop再Padding,每个操作仅能执行一次。3.色域转换在执行R......
  • 【2023 · CANN训练营第一季】应用开发深入讲解之模型转换工具
    应用开发深入讲解之模型转换工具1.基本概念昇腾张量编译器(AscendTensorCompiler,简称ATC)是异构计算架构CANN体系下的模型转换工具,它可以将开源框架的网络模型或AscendIR定义的单算子描述文件(json格式)转换为昇腾AI处理器支持的.om格式离线模型。模型转换过程中,ATC会进行算子调度......
  • 【2023 · CANN训练营第一季】应用开发深入讲解之模型离线推理
    应用开发深入讲解之模型离线推理模型离线推理是指使用已经转好的om模型对输入图片进行推理,主要步骤如下图所示:1.Host&Device内存管理与数据传输Host&Device上的内存申请与释放,内存间的相互拷贝。代码中加载输入数据时,需要申请Host内存进行存储,当输入数据处理完毕后,需要将处理完成的......
  • 【2023 · CANN训练营第一季】应用开发深入讲解之DVPP
    应用开发深入讲解之DVPP1.基本概念昇腾Al处理器内置图像处理单元DVPP(DigitalVideoPre-Processor),提供强大的媒体处理硬加速能力。主要功能模块有:2.常见接口a.内存申请与释放b.通道创建与释放c.图片描述信息创建与销毁d.图片描述参数设置3.JPEGD图片解码4.VPC视觉预处理......
  • 计算机操作系统中实现进程间同步的信号量概念讲解
    在计算机操作系统中,信号量(Semaphore)是一种用于实现进程间同步和互斥的机制。信号量提供了两个基本操作:P(Proberen)和V(Verhogen),它们在进程间进行同步操作。P(Proberen)操作:P操作也被称为"申请"操作或"阻塞"操作。当一个进程执行P操作时,它试图申请一个信号量。如果该信号量的值大于0,......
  • 卡尔曼滤波的讲解
    https://www.zhihu.com/question/23971601    ......