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项目模板

  • 添加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; }
}
}

效果

启动项目查看具体效果

默认进入登录界面,由于我们并没有授权信息,所以进入这个界面,然后我们随便输入一些内容点击登录。



当我们点击了登录按钮以后我们就进入到了MainLayout当中并且进入了首页。

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

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

结尾

来着token的分享

Blazor交流群:452761192

Blazor HyBrid 授权讲解的更多相关文章

  1. Blazor Hybrid / MAUI 简介和实战

    1. Blazor Blazor 是一个使用 .NET 生成交互式客户端 Web UI 的框架: 使用 C# 代替 JavaScript 来创建信息丰富的交互式 UI. 共享使用 .NET 编写的服务 ...

  2. Bootstrap Blazor Viewer 图片浏览器 组件更新, 支持流转图片(ImageFromStream), 用于本地项目例如 MAUI Blazor,Blazor hybrid

    示例: https://blazor.app1.es/viewer 使用方法: 1.nuget包 BootstrapBlazor.Viewer 2._Imports.razor 文件 或者页面添加 添 ...

  3. Blazor Hybrid (Blazor混合开发)更好的读取本地图片

    在 Blazor Hybrid 应用中,Razor 组件在设备上本机运行. 组件通过本地互操作通道呈现到嵌入式 Web View 控件. 组件不在浏览器中运行,并且不涉及 WebAssembly. R ...

  4. Blazor WebAssembly 3.2 正式发布

    5月 20日,微软 发布了 Blazor WebAssembly 3.2(https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0- ...

  5. Blazor和Vue对比学习:说在开始前

    1.Vue:现代前端三大框架之一(Vue/React/Angualr),基于HTML.CSS和JavaScript,2014年正式对外发布,目前已发展到3.X版本.值得说道的是,Vue的创始人作者是华 ...

  6. MAUI与Blazor共享一套UI,媲美Flutter,实现Windows、macOS、Android、iOS、Web通用UI

    1. 前言 距离上次发<MAUI初体验:爽>一文已经过去2个月了,本计划是下半年或者明年再研究MAUI的,现在计划提前啦,因为我觉得MAUI Blazor挺有意思的:在Android.iO ...

  7. MAUI Blazor 权限经验分享 (定位,使用相机)

    入门文章 Blazor Hybrid / MAUI 简介和实战 https://www.cnblogs.com/densen2014/p/16240966.html 在 Mac 上开发 .NET MA ...

  8. Blazor预研与实战

    背景 最近一直在搞一件事,就是熟悉Blazor,后期需要将Blazor真正运用到项目内.前期做了一些调研,包括但不限于 Blazor知识学习 组件库生态预研 与现有SPA框架做比对 与WebForm做 ...

  9. 【译】.NET 7 预览版 1 中的 ASP.NET Core 更新

    原文 | Daniel Roth 翻译 | 郑子铭 .NET 7 预览版 1 现已推出!这是 .NET 下一个主要版本的第一个预览版,其中将包括使用 ASP.NET Core 进行 Web 开发的下一 ...

  10. .NET Conf 2022 &ndash; 11 月 8 日至 10 日

    .NET Conf 2022 下周就正式开启了,时间是美国时间的 11月8日至10日..NET Conf 2022是一个免费的,为期三天的, 虚拟开发人员活动提供多种实时会话,其中包括来自社区和 .N ...

随机推荐

  1. RHCE服务---Web

    网站需求:请给openlab搭建web网站 1.基于域名www.openlab.com可以访问网站内容为 welcome to openlab!!! 2.给该公司创建三个子界面分别显示学生信息,教学资 ...

  2. 刷爆 LeetCode 双周赛 100,单方面宣布第一题最难

    本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 提问. 大家好,我是小彭. 上周末是 LeetCode 第 100 场双周赛,你参加了吗?这场周赛整体没有 Hard ...

  3. NodeJs的模块化和包

    模块化的基本概念 什么是模块化? 模块化是解决一个复杂问题时,自顶向下逐层把系统划分为若干个模块的过程,编程中,就是遵守一定规则,把一个大文件拆成独立并相互依赖的多个小模块. 模块化规范 使用什么样的 ...

  4. PHP微信三方平台-授权登录

    一.逻辑步骤解析 步骤 1:第三方平台方获取预授权码(pre_auth_code) 步骤 2:引入用户进入授权页 第三方平台方可以在自己的网站中放置"微信公众号授权"或者" ...

  5. 《程序是怎样跑起来的》读书笔记1——对程序员来说CPU是什么

    一丶什么是程序 程序是指令和数组的组合体,如:print("你好世界"),其中print是指令,你好世界是数据. CPU能直接识别和执行的只有机器语言,使用C,java这种高级语言 ...

  6. 强大的 apt-get 命令

    强大的 apt-get 命令(小结) 一.ubuntu下管理软件最方便的非 apt-get 工具莫属了,它的常见用法稍微整理一下供以后参考(详细见 man apt-get ): 1.更新源,升级软件和 ...

  7. [Linux]./configure | make | make install的工作过程与原理

    经常使用的Linux编译/安装命令,有必要了解一下原理了. step1 ./configure 配置与编译前检查 通常由软件开发商编写一个检测程序(configure或config)来检测用户的操作环 ...

  8. [J2EE:中间件]LOG4J及配置文件(log4j.properties)详解

    1 简介 日志是应用软件中不可缺少的部分,Apache的开源项目log4j是一个功能强大的日志组件,提供方便的日志记录.在apache网站:jakarta.apache.org/log4j 可以免费下 ...

  9. 逍遥自在学C语言 位运算符 "|" 的5种高级用法

    前言 在上一篇文章中,我们介绍了&运算符的高级用法,本篇文章,我们将介绍| 运算符的一些高级用法. 一.人物简介 第一位闪亮登场,有请今后会一直教我们C语言的老师 -- 自在. 第二位上场的是 ...

  10. linux 安装 node 和 npm 服务

    1.安装文件下载 下载地址:https://nodejs.org/zh-cn/download/ 2.安装步骤 1.将安装包上传到指定位置(我习惯放到:/usr/local/application/目 ...