如果代码生成出错
卸载 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. 2020年10月ICPC & 天梯赛 选拔赛【ACFJ】

    A. 表达式 题意 题解 将所有数字替换为A,运算符替换为O,然后不断合并(AOA),判断表达式最后是否为A即可. 注意将数字替换时判断有无前导零. 代码 #include <bits/stdc ...

  2. 牛客15334 Easygoing Single Tune Circulation(后缀自动机+字典树)

    传送门:Easygoing Single Tune Circulation 题意 给定n个字符串 s[i],再给出m个查询的字符串 t[i],问 t[i] 是否为某个 s[i] 循环无限次的子串. 题 ...

  3. int和longlong的范围

    unsigned   int     0-4294967295   (10位数,4e9) int                        -2147483648-2147483647  (10位 ...

  4. STL中pair容器的用法

    1.定义pair容器 1 pair <int, int> p, p1; 2 //定义 [int,int] 型容器 //直接初始化了p的内容 pair<string,int>p( ...

  5. 仿ATM程序软件

    一.目标: ATM仿真软件 1 系统的基本功能 ATM的管理系统其基本功能如下:密码验证机制:吞锁卡机制:存取款功能:账户查询功能:转账功能等. 要求 要能提供以下几个基本功能: (1)系统内的相关信 ...

  6. Codeforces Round #515 (Div. 3) C. Books Queries (模拟)

    题意:有一个一维的书架,\(L\)表示在最左端放一本书,\(R\)表示在最右端放一本书,\(?\)表示从左数或从右数,最少数多少次才能得到要找的书. 题解:我们开一个稍微大一点的数组,从它的中间开始模 ...

  7. 01.原生态jdbc程序中问题总结

    1.数据库启动包配置到工程目录中(mysql5.1) mysql-connector-java-5.1.7-bin.jar 2.jdbc原生态操作数据库(程序) 操作mysql数据库 1 packag ...

  8. CF1415-C. Bouncing Ball

    CF1415-C. Bouncing Ball 题意: 在\(x\)轴上有\(n\)个点(从\(1\)到\(n\)),每个点都有一个值\(0\)或\(1\),\(0\)代表这个点不能走,\(1\)代表 ...

  9. Chrony时间同步

    chrony 服务器 yum -y install chrony cp /etc/chrony.conf{,.bak} #备份默认配置 cat > /etc/chrony.conf <&l ...

  10. 网络安全-WEB基础,burpsuite,WEB漏洞

    1. web基础 HTTP: GET POST REQUEST RESPONSE... JDK robots.txt 网页源代码/注释 目录扫描--御剑,dirmap 端口信息--nmap 备份文件- ...