Blazor入门100天 : 身份验证和授权 (2) - 角色/组件/特性/过程逻辑
目录
- 建立默认带身份验证 Blazor 程序
- `角色/组件/特性/过程逻辑
- DB 改 Sqlite
- 将自定义字段添加到用户表
- 脚手架拉取IDS文件,本地化资源
- freesql 生成实体类,freesql 管理ids数据表
- 初始化 Roles,freesql 外键 => 导航属性
- 完善 freesql 和 bb 特性
本节源码
https://github.com/densen2014/Blazor100/tree/Blazor-教程15-2/b15blazorIDS
更改默认密码策略,添加管理员角色
有些同学说一直使用1qaz@WSX密码感觉不爽,那我们改一下策略
编辑Program.cs文件
找到
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
改为以下配置
builder.Services.AddDefaultIdentity<IdentityUser>(o =>
{ // Password settings.
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequireUppercase = false;
o.Password.RequiredLength = 1;
o.Password.RequiredUniqueChars = 1;
}
)
.AddRoles<IdentityRole>()
编辑页面Index.razor
页面头部加入
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Identity
@using System.Diagnostics.CodeAnalysis
初始化角色,添加默认管理员
最终页面代码
@code
{
[Inject]
[NotNull]
protected UserManager<IdentityUser>? UserManager { get; set; }
[Inject]
[NotNull]
protected RoleManager<IdentityRole>? RoleManager { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
var RoleResult = await RoleManager.FindByNameAsync(AuthorizeRoles.Admin.ToString());
if (RoleResult == null)
{
await RoleManager.CreateAsync(new IdentityRole(AuthorizeRoles.Admin.ToString()));
Console.WriteLine("Admin Role Created");
}
var user = await UserManager.FindByNameAsync("test@app.com");
if (user != null)
{
var UserResult = await UserManager.IsInRoleAsync(user, AuthorizeRoles.Admin.ToString());
if (!UserResult)
{
await UserManager.AddToRoleAsync(user, AuthorizeRoles.Admin.ToString());
Console.WriteLine("Admin Role Added to test@app.com");
}
}
var chekRole = RoleManager.RoleExistsAsync(AuthorizeRoles.R110.ToString());
if (chekRole.Result == false)
{
await RoleManager.CreateAsync(new IdentityRole(AuthorizeRoles.R110.ToString()));
Console.WriteLine("R110Role Created");
}
chekRole = RoleManager.RoleExistsAsync(AuthorizeRoles.Superuser.ToString());
if (chekRole.Result == false)
{
await RoleManager.CreateAsync(new IdentityRole(AuthorizeRoles.Superuser.ToString()));
Console.WriteLine("Superuser Role Created");
}
}
public enum AuthorizeRoles
{
Admin,
Superuser,
R110,
R120,
R130,
R140,
}
}
参考第一篇重新注册账号, 点击 Register 注册账号
| Password | Confirm Password | |
|---|---|---|
| test@app.com | 000000 | 000000 |
登录后,刷新两次首页,test@app.com就会被代码设置为管理员组

<AuthorizeView>组件
编辑 Index.razor 文件,加入以下代码
<AuthorizeView>
<Authorized>
你好, @context.User.Identity?.Name
@if (@context.User.IsInRole(AuthorizeRoles.Administrators.ToString()))
{
<span>管理员</span>
}
else if (@context.User.IsInRole(AuthorizeRoles.Superuser.ToString()))
{
<span>超级用户</span>
}
else
{
<span>能力者</span>
}
</Authorized>
<NotAuthorized>
<span>看起来你还没登录</span>
</NotAuthorized>
</AuthorizeView>
@code{
public enum AuthorizeRoles
{
Superuser,
Administrators,
R110,
R120,
R130,
R140,
}
}
运行截图

检查登录信息
新建Razor组件: LogInfo


编辑页面
@page "/logInfo"
<PageTitle>登录信息</PageTitle>
<h1>登录信息</h1>
<button @onclick="LogUsername">检查登录信息</button>
<p>@authMessage</p>
@code
{
/// <summary>
/// 级联参数获取身份验证状态数据
/// </summary>
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private string authMessage;
private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
authMessage = $"{user.Identity.Name} is authenticated.";
}
else
{
authMessage = "The user is NOT authenticated.";
}
}
}
运行

添加导航菜单
编辑文件 Shared\NavMenu.razor

<div class="nav-item px-3">
<NavLink class="nav-link" href="logInfo">
<span class="oi oi-plus" aria-hidden="true"></span> 登录信息
</NavLink>
</div>
注销按钮
编辑 Index.razor 文件,加入以下代码
@using Microsoft.AspNetCore.Components.Authorization
<form method="post" action="Identity/Account/Logout">
<button type="submit" class="nav-link btn btn-link">Log out</button>
</form>
基于策略的授权 / 基于角色或基于策略的授权
基于策略的授权需要Program.cs添加相关配置,这里带过就好,不展开讨论.
<p>基于角色或基于策略的授权 </p>
<AuthorizeView Roles="Admin, Superuser">
<p>You can only see this if you're an Admin or Superuser.</p>
</AuthorizeView>
<p>基于策略的授权</p>
<AuthorizeView Policy="ContentEditor">
<p>You can only see this if you satisfy the "ContentEditor" policy.</p>
</AuthorizeView>
在 Razor 组件中使用 [Authorize] 特性
新建AuthorizePage.razor组件
@page "/AuthorizePage"
@attribute [Authorize]
<PageTitle>已登录</PageTitle>
<h1>You can only see this if you're signed in.</h1>
导航菜单Shared\NavMenu.razor
<div class="nav-item px-3">
<NavLink class="nav-link" href="AuthorizePage">
<span class="oi oi-plus" aria-hidden="true"></span> 验证组件
</NavLink>
</div>
未登录状态

登录后状态

在 Razor 组件中使用 [Authorize(Roles = "Admin, Superuser")] 特性
新建AuthorizeAdminPage.razor组件
@page "/AuthorizeAdminPage"
@attribute [Authorize(Roles = "Admin, Superuser")]
<PageTitle>Admin 已登录</PageTitle>
<p>You can only see this if you're in the 'Admin' or 'Superuser' role.</p>
导航菜单Shared\NavMenu.razor
<div class="nav-item px-3">
<NavLink class="nav-link" href="AuthorizeAdminPage">
<span class="oi oi-plus" aria-hidden="true"></span> Admin验证组件
</NavLink>
</div>
管理员账号test@app.com登录

普通账号test@test.com登录

过程逻辑中检查授权规则 AuthenticationState
新建AuthenticationStatePage.razor组件
@page "/AuthenticationStatePage"
@attribute [Authorize]
<PageTitle>Admin 已登录</PageTitle>
<pre>如果需要应用在过程逻辑中检查授权规则,请使用类型为 Task<AuthenticationState> 的级联参数来获取用户的 ClaimsPrincipal。 Task<AuthenticationState> 可以与其他服务(如 IAuthorizationService)结合使用来评估策略。</pre>
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
<button @onclick="@DoSomething">Do something important</button>
<p>@Msg</p>
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private string? Msg { get; set; }
private async Task DoSomething()
{
var user = (await authenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
Msg = "Perform an action only available to authenticated (signed-in) users.";
}
if (user.IsInRole("admin"))
{
Msg = "Perform an action only available to users in the 'admin' role.";
}
//if ((await AuthorizationService.AuthorizeAsync(user, "content-editor"))
// .Succeeded)
//{
// Msg = "Perform an action only available to users satisfying the 'content-editor' policy.";
//}
}
}
导航菜单Shared\NavMenu.razor
<div class="nav-item px-3">
<NavLink class="nav-link" href="AuthenticationStatePage">
<span class="oi oi-plus" aria-hidden="true"></span> 验证过程逻辑
</NavLink>
</div>

本节源码
https://github.com/densen2014/Blazor100/tree/Blazor-教程15-2/b15blazorIDS
源代码
https://github.com/densen2014/Blazor100
https://gitee.com/densen2014/Blazor100 (镜像/非最新版)
Blazor入门100天 : 身份验证和授权 (2) - 角色/组件/特性/过程逻辑的更多相关文章
- ASP.NET Web API身份验证和授权
英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-a ...
- ASP.NET MVC5学习系列——身份验证、授权
一.什么是身份验证和授权 人们有时对用户身份验证和用户授权之间的区别感到疑惑.用户身份验证是指通过某种形式的登录机制(包括用户名/密码.OpenID.OAuth等说明身份的项)来核实用户的身份.授权验 ...
- 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分
原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...
- 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权
OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...
- 使用 cookie 的身份验证和授权
前言 在上一章 学学 dotnet core 中的身份验证和授权-1-概念 中,我们大致明白了身份验证和授权两者的关系.那么在本文中,我们将使用 cookie 来做一个简单的身份验证和授权. 本文中我 ...
- 学学dotnet core中的身份验证和授权-1-概念
前言 身份验证: Authentication 授权: Authorization net core 中的身份验证和授权这两个部分,是相辅相成的.当初我在学在部分的时候,是看的 net core 官网 ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- ASP.NET MVC5(五):身份验证、授权
使用Authorize特性进行身份验证 通常情况下,应用程序都是要求用户登录系统之后才能访问某些特定的部分.在ASP.NET MVC中,可以通过使用Authorize特性来实现,甚至可以对整个应用程序 ...
- mongo的身份验证和授权
问题来源 刚装好的mongo,准备登陆进去测一把的,结果就给我报这个错,鄙人是新手,还不太清楚这个,现学一下~ Mongo的身份验证 在上一篇安装mongo的博客中(https://www.cnblo ...
- shiro系列二、身份验证和授权
一.身份验证 先来看看身份验证的流程 流程如下: 1.首先调用Subject.login(token)进行登录,其会自动委托给Security Manager,调用之前必须通过SecurityUtil ...
随机推荐
- spring-ioc知识点
1.bean管理 -spring创建对象 -在spring的配置文件中,使用bean标签.标签里添加对应的属性.就可以实现对象的创建 -在bean标签中有很多属性 -id属性:唯一的标识 -class ...
- 论文笔记 - PRISM: A Rich Class of Parameterized Submodular Information Measures for Guided Subset Selection
Motivation 与 Active Learning 类似,Target Learning 致力于 挑选外卖更"感兴趣"的数据,即人为为更重要的数据添加 bias.例如我们当前 ...
- 畅联新增物联网设备接入协议:精华隆的NB一键报警
这个是有点时间了,这里记录一下! ----------------------------------------------------------------------------------- ...
- 【题解】CF1013B And
题面传送门 解决思路 首先我们可以得出,$ a $ \(\&\) $ x $ \(=\) $ a $ \(\&\) $ x $ \(\&\) $ x $.由此得知,同一个 \( ...
- ElasticSearch 常见问题
ElasticSearch 常见问题 丈夫有泪不轻弹,只因未到伤心处. 1.说说 es 的一些调优手段. 仅索引层面调优手段: 1.1.设计阶段调优 (1)根据业务增量需求,采取基于日期模板创建索引, ...
- c#入参使用引用类型为啥要加ref?
摘一段来自官网的说明 :方法的参数列表中使用 ref 关键字时,它指示参数按引用传递,而非按值传递. ref 关键字让形参成为实参的别名,这必须是变量. 换而言之,对形参执行的任何操作都是对实参执行的 ...
- UED Landing 页 - 定时抓取掘金文章
我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品.我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值. 本文作者:琉易 https://liuxianyu.cn 本次分享基 ...
- Redis 常见问题
Redis 常见问题 落叶他乡树,寒灯独夜人. 一. 什么是Redis? Redis 是一个使用 C 语言写成的,开源的高性能key-value非关系缓存数据库: Redis的数据都基于缓存的,所以很 ...
- salesforce零基础学习(一百二十一)Limitation篇之Heap Size Limitation
本篇参考: https://help.salesforce.com/s/articleView?id=000384468&type=1 https://help.salesforce.com/ ...
- python-面向过程与函数式
面向过程与函数式 面向过程 "面向过程"核心是"过程"二字,"过程"指的是解决问题的步骤,即先干什么再干什么......,基于面向过程开发程 ...