如果代码生成出错
卸载 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. 2019牛客暑期多校训练营(第五场)C - generator 2 (BSGS)

    题目链接 题意: 给定\(n,x_0,a,b,p\),有递推式\(x_i = (a \cdot x_{i-1} +b)\%p\). 有\(Q\)个询问,每次询问给定一个\(v\),问是否存在一个最小的 ...

  2. 关于贪心算法的经典问题(算法效率 or 动态规划)

    如题,贪心算法隶属于提高算法效率的方法,也常与动态规划的思路相挂钩或一同出现.下面介绍几个经典贪心问题.(参考自刘汝佳著<算法竞赛入门经典>).P.S.下文皆是我一个字一个字敲出来的,绝对 ...

  3. Codeforces Round #689 (Div. 2, based on Zed Code Competition) E. Water Level (贪心好题)

    题意:你在一家公司工作\(t\)天,负责给饮水机灌水,饮水机最初有\(k\)升水,水的范围必须要在\([l,r]\)内,同事每天白天都会喝\(x\)升水,你在每天大清早可以给饮水机灌\(y\)升水,问 ...

  4. C# 替换文件名的字符

    https://www.cnblogs.com/lindexi/p/8970466.html

  5. 【ybt金牌导航1-2-6】【luogu P2467】地精部落

    地精部落 题目链接:ybt金牌导航1-2-6 / luogu P2467 题目大意 有一个排列,要使得每个位置要么都比两边高,要么比两边低. 而且一定要以一高一低的方式排列. 两边的只用比旁边的那个高 ...

  6. 洛谷P1522 [USACO2.4]牛的旅行 Cow Tours

    洛谷P1522 [USACO2.4]牛的旅行 Cow Tours 题意: 给出一些牧区的坐标,以及一个用邻接矩阵表示的牧区之间图.如果两个牧区之间有路存在那么这条路的长度就是两个牧区之间的欧几里得距离 ...

  7. 2019牛客多校第二场E MAZE(线段树 + 矩阵)题解

    题意: n * m的矩阵,为0表示可以走,1不可以走.规定每走一步只能向下.向左.向右走.现给定两种操作: 一.1 x y表示翻转坐标(x,y)的0.1. 二.2 x y表示从(1,x)走到(n,y) ...

  8. Windows 10 & git & bash

    Windows 10 & git & bash If you are on Windows, we recommend downloading Git for Windows and ...

  9. popstate 事件 & history API

    popstate 事件 & history API URL change 当用户浏览会话历史记录时,活动历史记录条目发生更改时,将触发 Window 界面的 popstate 事件. 它将当前 ...

  10. Chrome V8 系统架构

    Chrome V8 系统架构 Chromium 多进程多线程架构 design-documents https://www.chromium.org/developers/design-documen ...