我使用 Blazor 的 Windows 身份验证来对用户进行身份验证。现在我也想授权这些用户,我通过让用户在数据库表中滚动和 userId 来做到这一点,如下所示:
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);
}
}
}
正如您在屏幕截图中看到的,数据库查询有效。我现在遇到的以下问题是在index.razor中,如第二个屏幕截图所示PS:我认为问题是通过创建新的 ClaimsPrincipal 我覆盖了 Windows 身份验证。我制作了一个全新的syncfusion blazor服务器应用程序,并仅将我的项目中的身份验证部分放入新的应用程序中,因此我可以尝试一切,但没有任何效果。
编辑:我什至从用户变量
@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 工作正常并显示:“你好,
用户名!”