如何在 blazor 中进行身份验证和授权

问题描述 投票:0回答:1

我使用 Blazor 的 Windows 身份验证来授权

用户ID角色ID31711121427282
实际授权发生在 CustomAuthenticationStateRrovider.cs 中

using Microsoft.AspNetCore.Components.Authorization; using System.Diagnostics; using System.Security.Claims; namespace Authtest.Services { public class CustomAuthenticationStateProvider : AuthenticationStateProvider { private List<UserRoles> userRoles = default!; public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var userroleService = new UserRoleService(); userRoles = userroleService.GetUserRolesListe(); var identity = new ClaimsIdentity(); foreach (var role in userRoles) { Debug.WriteLine($"Adding role {role.RoleId} to identity."); identity.AddClaim(new Claim(ClaimTypes.Role, role.RoleId.ToString())); } var user = new ClaimsPrincipal(identity); return new AuthenticationState(user); } } }
正如您在屏幕截图中看到的,数据库查询有效。

Debug var user

我现在遇到的以下问题是在index.razor中,如第二个屏幕截图所示

problem with auth,尽管我的用户具有角色1,但显示了授权部分,并且只有具有角色2的用户应该看到文本。 LoginDisplay.razor 的一个不同问题(这取决于我认为的相同解决方案)是为什么总是显示 NotAuthorized 部分。

PS:我认为问题是通过创建新的 ClaimsPrincipal 我覆盖了 Windows 身份验证。

我制作了一个全新的syncfusion blazor服务器应用程序,并仅将我的项目中的身份验证部分放入新的应用程序中,因此我可以尝试一切,但没有任何效果。

编辑:我什至从用户变量

here制作了更详细的屏幕截图。

c# authentication blazor authorization blazor-server-side
1个回答
0
投票
好吧,经过一些研究和这篇文章的评论,我尝试了一些不同的东西。

@page "/" @using System.Diagnostics @using System.Security.Claims @using Authtest.Services @inject AuthenticationStateProvider AuthenticationStateProvider @inject UserRoleService UserRoleService <PageTitle>Index</PageTitle> <AuthorizeView Roles="1"> <Authorized> <p>This content is displayed only for users with role 1.</p> </Authorized> <NotAuthorized> <p>This content is displayed for all other roles and non-authorized users. </p> </NotAuthorized> </AuthorizeView> @code{ private List<string> userRoles = new List<string>(); protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { var username = user.Identity.Name; var roles = UserRoleService.GetUserRolesListe().Where(ur => ur.WindowsUser == username).Select(ur => ur.RoleId.ToString()).ToList(); var identity = (ClaimsIdentity)user.Identity; identity.AddClaims(roles.Select(role => new Claim(ClaimTypes.Role, role))); foreach (var claim in identity.Claims.Where(c => c.Type == ClaimTypes.Role)) { Debug.WriteLine($"User {user.Identity.Name} has role: {claim.Value}"); } } await base.OnInitializedAsync(); } }
我从 Debug.WriteLine 得到的结果是这样的:“用户 QUANDT\jorge.ferreira 的角色:1”

但我仍然得到 NotAuthorized View Part(此内容针对所有其他角色和非授权用户显示。)

我的 LoginDisplay.razor 工作正常并显示:“你好,

用户名!”

© www.soinside.com 2019 - 2024. All rights reserved.