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("[email protected]");
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 [email protected]");
}
}
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,
}
}
Password | Confirm Password | |
---|---|---|
[email protected] | 000000 | 000000 |
<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>
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>
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>
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 (映象/非最新版)
FreeSql QQ群:4336577
BA & Blazor QQ群:795206915
本作品採用 知識共用署名-非商業性使用-相同方式共用 4.0 國際許可協定 進行許可。歡迎轉載、使用、重新發布,但務必保留文章署名AlexChow(包含連結: https://github.com/densen2014 ),不得用於商業目的,基於本文修改後的作品務必以相同的許可釋出。如有任何疑問,請與我聯絡 。
本文來自部落格園,作者:周創琳 AlexChow,轉載請註明原文連結:https://www.cnblogs.com/densen2014/p/17083932.html
今日頭條 | 部落格園 | 知乎 | Gitee | GitHub