如果代码生成出错
卸载 Microsoft.AspNetCore.Identity.UI ,再安装,然后运行添加基架项目
 
运行项目
 
在 BlazorApp0228\Shared\   添加  LoginDisplay.razor
 
<AuthorizeView>
<Authorized>
<a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
<form method="post" action="Identity/Account/LogOut">
<button type="submit" class="nav-link btn btn-link">Log out</button>
</form>
</Authorized>
<NotAuthorized>
<a href="Identity/Account/Register">Register</a>
<a href="Identity/Account/Login">Log in</a>
</NotAuthorized>
</AuthorizeView>
 
在 APP.razor  增加嵌套
 
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<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>
 
在 MainLayout.razor 添加 LoginDisplay
 
在 setup 设置
Routing 后增加
        app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication();//add
app.UseAuthorization();//add app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
 
修改 Areas.Identity.IdentityHostingStartup 注册选项
运行,如出现错误:

SqlException: Cannot open database "BlazorTest228" requested by the login.

 
则迁移生成数据库
 
PM> Add-Migration Test228V1
PM> Update-Database
 
 
添加自定义用户数据
 
    public class BlazorTest228User : IdentityUser
{
[PersonalData]
public string CustomName { get; set; }
}
 
PM> Add-Migration Test228V1.1
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Done.
 

更新 "帐户/管理/索引" 页

InputModel用以下突出显示的代码更新 区域/ Identity /Pages/Account/Manage/Index.cshtml.cs 中的:
 
public class InputModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Custom name")]
public string CustomName { get; set; } [Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
} private async Task LoadAsync(BlazorTest228User user)
{
var userName = await _userManager.GetUserNameAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel
{
CustomName = user.CustomName,
PhoneNumber = phoneNumber
};
} if (Input.CustomName != user.CustomName)
{
user.CustomName = Input.CustomName;
} await _userManager.UpdateAsync(user); await _signInManager.RefreshSignInAsync(user);
 
用以下突出显示的标记更新 区域/ Identity /Pages/Account/Manage/Index.cshtml :
<form id="profile-form" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.CustomName"></label>
<input asp-for="Input.CustomName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
 更新帐户/注册. cshtml 页
InputModel用以下突出显示的代码更新 区域/ Identity /Pages/Account/Register.cshtml.cs 中的:
public class InputModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Custom name")]
public string CustomName { get; set; } [Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; } public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new BlazorTest228User { CustomName = Input.CustomName, UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
用以下突出显示的标记更新 区域/ Identity /Pages/Account/Register.cshtml :
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.CustomName"></label>
<input asp-for="Input.CustomName" class="form-control" />
<span asp-validation-for="Input.CustomName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
 
 
 
修改LoginDisplay.razor 显示自定义字段
 
@using Microsoft.AspNetCore.Identity
@using BlazorTest228.Areas.Identity.Data
@inject UserManager<BlazorTest228User> UserManager
<AuthorizeView>
<Authorized>
@*<a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>*@
<a href="Identity/Account/Manage">
@UserManager.GetUserAsync(context.User).Result.CustomName
</a>
<form method="post" action="Identity/Account/LogOut">
<button type="submit" class="nav-link btn btn-link">Log out</button>
</form>
</Authorized>
<NotAuthorized>
<a href="Identity/Account/Register">Register</a>
<a href="Identity/Account/Login">Log in</a>
</NotAuthorized>
</AuthorizeView>
 
 
为页面添加访问许可
 
1)\Areas\Identity\IdentityHostingStartup.cs
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
services.AddDbContext<BlazorTest228Context>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("BlazorTest228ContextConnection"))); services.AddDefaultIdentity<BlazorTest228User>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<BlazorTest228Context>();
});
}
}
 2)app.razor  修改为
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData"
DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<h1>Sorry</h1>
<p>You're not authorized to reach this page.</p>
<p>You may need to log in as a different user.</p>
</NotAuthorized>
<Authorizing>
<h1>Authorization in progress</h1>
<p>Only visible while authorization is in progress.</p>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<h1>Sorry</h1>
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
3)要求登陆的页面增加
@page "/counter"
@attribute [Authorize] <h1>Counter</h1>
效果
 
 
对于页面局部内容,直接使用
<AuthorizeView>
<Authorized>
<h1>Hello, @context.User.Identity.Name!</h1>
<p>登陆后显示的内容</p>
</Authorized>
<NotAuthorized>
<h1>未登陆时的信息</h1>
<p>用户尚未登陆</p>
</NotAuthorized>
</AuthorizeView>
 
 

使用.net5 创建具有身份验证和授权的Blazor应用程序的更多相关文章

  1. 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权

    OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...

  2. ASP.NET Web API身份验证和授权

    英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-a ...

  3. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分

    原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...

  4. ASP.NET MVC5学习系列——身份验证、授权

    一.什么是身份验证和授权 人们有时对用户身份验证和用户授权之间的区别感到疑惑.用户身份验证是指通过某种形式的登录机制(包括用户名/密码.OpenID.OAuth等说明身份的项)来核实用户的身份.授权验 ...

  5. 使用 cookie 的身份验证和授权

    前言 在上一章 学学 dotnet core 中的身份验证和授权-1-概念 中,我们大致明白了身份验证和授权两者的关系.那么在本文中,我们将使用 cookie 来做一个简单的身份验证和授权. 本文中我 ...

  6. 学学dotnet core中的身份验证和授权-1-概念

    前言 身份验证: Authentication 授权: Authorization net core 中的身份验证和授权这两个部分,是相辅相成的.当初我在学在部分的时候,是看的 net core 官网 ...

  7. ASP.NET WEBAPI 的身份验证和授权

    定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...

  8. ASP.NET MVC5(五):身份验证、授权

    使用Authorize特性进行身份验证 通常情况下,应用程序都是要求用户登录系统之后才能访问某些特定的部分.在ASP.NET MVC中,可以通过使用Authorize特性来实现,甚至可以对整个应用程序 ...

  9. mongo的身份验证和授权

    问题来源 刚装好的mongo,准备登陆进去测一把的,结果就给我报这个错,鄙人是新手,还不太清楚这个,现学一下~ Mongo的身份验证 在上一篇安装mongo的博客中(https://www.cnblo ...

随机推荐

  1. D-DP

    必备知识 ​ 树链剖分,最大权独立集(即没有上司的舞会(树上DP)),矩阵乘法; D-DP 模版简述 ​ 模板 ​ 关于动态DP,其实是关于一类动态修改点权的问题,但是很难去处理; ​ 我们平常的DP ...

  2. 利用github+hexo搭建的博客

    用github+hexo新建了一个博客,欢迎来访,如果想要搭建类似框架的博客,可以联系我. 新博客地址:只为自由书写的博客

  3. 2019ICPC南昌邀请赛 Sequence

    题意:给出n个点的权值,m次操作,操作为1时为询问,每次询问给出 l 和 r ,求 f(l,r).操作为0时为修改权值.f(l,r)=f(l,l)⊕f(l,l+1)⊕⋯⊕f(l,r)⊕f(l+1,l+ ...

  4. 【bzoj 2339】[HNOI2011]卡农(数论--排列组合+逆元+递推)

    题意:从编号为 1~N 的音阶中可选任意个数组成一个音乐片段,再集合组成音乐篇章.要求一个音乐篇章中的片段不可重复,都不为空,且出现的音符的次数都是偶数个.问组成 M 个片段的音乐篇章有多少种.答案取 ...

  5. POJ - 2553 tarjan算法+缩点

    题意: 给你n个点,和m条单向边,问你有多少点满足(G)={v∈V|∀w∈V:(v→w)⇒(w→v)}关系,并把这些点输出(要注意的是这个关系中是蕴含关系而不是且(&&)关系) 题解: ...

  6. C#枚举(一)使用总结以及扩展类分享

    0.介绍 枚举是一组命名常量,其基础类型为任意整型. 如果没有显式声明基础类型, 则为Int32 在实际开发过程中,枚举的使用可以让代码更加清晰且优雅. 最近在对枚举的使用进行了一些总结与整理,也发现 ...

  7. Cobbler自定义安装系统和私有源

    1.自定义安装系统(根据mac地址) --name=定义名称 --mac=客户端的mac地址 --ip-address=需求的ip --subnet=掩码 --gateway=网关 --interfa ...

  8. 牛客多校第八场E Explorer(左开右闭线段树+可撤回并查集)题解

    题意: 传送门 有\(n\)个点构成一个无向图,每条边有\(L_i,R_i\)表示这条边只能允许编号为\(L_i\dots R_i\)的人通过,现在问你最多有几个人能从\(1\)走到\(n\). 思路 ...

  9. Front End Frameworks Trending 2021

    Front End Frameworks Trending 2021 Front End Frameworks https://2019.stateofjs.com/front-end-framewo ...

  10. free online markdown editor

    free online markdown editor markdown https://blog.csdn.net/xgqfrms/article/details/50129317 In-brows ...