C#修改标识或添加声明



应用程序是Blazor服务器。NET Core 5.0

我正在使用。NET Core的标识系统和我遇到了一个问题。我想把这个人的名字和身份一起存储起来,这样我就可以很容易地调用它。

目前,我有一个类覆盖基本标识:

public class ApplicationUser : IdentityUser
{
public ApplicationUser() : base() { }
[StringLength(100)]
public string FirstName { get; set; }
[StringLength(100)]
public string LastName { get; set; }
}

我的startup.cs有:

services.AddDefaultIdentity<ApplicationUser>(options => {
options.SignIn.RequireConfirmedAccount = true;
}
)

在我看来,这应该迫使程序的intellisense理解ApplicationUser是查找标识时的默认类。

然而,当我尝试呼叫时:

var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

它只返回";IdentityUser";数据,而不是我的自定义ApplicationUser类。

AuthenticationStateProvider返回的内容或类型转换是否缺少某些内容?

此外,如果这是完全不正确的,我应该对索赔进行处理吗?如果是这样的话,我就找不到一种具体的方法来有效地使用Blazor服务器的声明。

public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

在Package Manager控制台中执行:

  1. 添加迁移CreateAppUser
  2. 更新数据库

在用户表中创建的FirstName和LastName中插入值

创建一个名为ApplicationUserClaimsTransformation 的类

ApplicationUserClaimsTransformation.cs

using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication3.Data;
using WebApplication3.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Authorization;
public class ApplicationUserClaimsTransformation : IClaimsTransformation
{
private readonly UserManager<ApplicationUser> _userManager;
public ApplicationUserClaimsTransformation(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}

public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identity = principal.Identities.FirstOrDefault(c => c.IsAuthenticated);
if (identity == null) return principal;
var user = await _userManager.GetUserAsync(principal);
if (user == null) return principal;
// Add or replace identity.Claims.

if (!principal.HasClaim(c => c.Type == ClaimTypes.GivenName))
{
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName));

}
if (!principal.HasClaim(c => c.Type == ClaimTypes.Surname))
{
identity.AddClaim(new Claim(ClaimTypes.Surname, user.LastName));
}
return new ClaimsPrincipal(identity);
}
}

启动。配置服务

services.AddScoped<IClaimsTransformation, 
ApplicationUserClaimsTransformation>();

索引.razor

@page "/"
@inject AuthenticationStateProvider AuthState
@using System.Security
@using System.Security.Claims
@foreach(var c in user.Claims)
{
<div>@c.Type:  @c.Value</div>
}
@code
{
private ClaimsPrincipal user;
protected override async Task OnInitializedAsync()
{
var x = await AuthState.GetAuthenticationStateAsync();
user =  x.User;
await base.OnInitializedAsync();
}
}

注意:您应该在中将IdentityUser名称更改为ApplicationUserStartup类、LogOut.cshtml文件、_LoginPartial.cshhtml文件和在ApplicationDbContext类的定义中:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

相关内容

  • 没有找到相关文章

最新更新