首页 > 其他分享 >在 .net 8 Blazor Identity 中添加Claim

在 .net 8 Blazor Identity 中添加Claim

时间:2024-01-20 09:55:57浏览次数:26  
标签:Claim Nick userInfo var new net Blazor principal

.net 8 Blazor Identity 使用 Individual Account 模版时,默认的UserInfo 只有Id,Email 和 UserName。 如果想让客户端共享更多用户信息,可以使用自定义的ClaimsPrincipalFactory。代码如下:

public class FlowYogaClaimsPrincipalFactory(UserManager<YourCustomUserClass> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor)
    : UserClaimsPrincipalFactory<YourCustomUserClass, IdentityRole>(userManager, roleManager, optionsAccessor)
{
    protected override async Task<ClaimsIdentity> GenerateClaimsAsync(YourCustomUserClass user)
    {
        var identity = await base.GenerateClaimsAsync(user);
        identity.AddClaim(new Claim("Nick", $"{user.Nick}"));
        identity.AddClaim(new Claim("Nick", $"{user.Icon}"));
        return identity;
    }
}

 这里我加入了用户的昵称和图标两个新值。服务端序列化时要修改 PersistingRevalidatingAuthenticationStateProvider.cs

private async Task OnPersistingAsync()
{
    if (authenticationStateTask is null)
    {
        throw new UnreachableException($"Authentication state not set in {nameof(OnPersistingAsync)}().");
    }

    var authenticationState = await authenticationStateTask;
    var principal = authenticationState.User;

    if (principal.Identity?.IsAuthenticated == true)
    {
        var userId   = principal.FindFirst(options.ClaimsIdentity.UserIdClaimType)?.Value;
        var email    = principal.FindFirst(options.ClaimsIdentity.EmailClaimType)?.Value;
        var userName = principal.FindFirst(options.ClaimsIdentity.UserNameClaimType)?.Value;
        var nick     = principal.FindFirst("Nick")?.Value;
        var icon     = principal.FindFirst("Icon")?.Value;
        
        if (userId != null && email != null)
        {
            state.PersistAsJson(nameof(UserInfo), new UserInfo
            {
                UserName = userName,
                UserId = userId,
                Email = email,
                Nick = nick,
                Icon = icon
            });
        }
    }
}

 WASM客户端工程里的PersistentAuthenticationStateProvider.cs也要修改:

public PersistentAuthenticationStateProvider(PersistentComponentState state)
{
    if (!state.TryTakeFromJson<UserInfo>(nameof(UserInfo), out var userInfo) || userInfo is null)
    {
        return;
    }

    Claim[] claims =
    [
        new Claim(ClaimTypes.NameIdentifier, userInfo.UserId),
        new Claim(ClaimTypes.Name, userInfo.UserName),
        new Claim(ClaimTypes.Email, userInfo.Email),
        new Claim("Nick", userInfo.Nick),
        new Claim("Icon", userInfo.Icon)
    ];

    authenticationStateTask = Task.FromResult(
        new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims,
            authenticationType: nameof(PersistentAuthenticationStateProvider)))));
}

 WASM组件读取就可以了

<AuthorizeView>
    Hello @context.User.Identity?.Name!

    <br />Your Nick: @context.User.FindFirst("Nick")?.Value

</AuthorizeView>

 

标签:Claim,Nick,userInfo,var,new,net,Blazor,principal
From: https://www.cnblogs.com/LogoCodr/p/17976064

相关文章

  • .NET字符串内存管理:常量字符串、动态创建和字符串池的巧妙结合
     在.NET中,字符串是不可变的,这意味着一旦创建,字符串的内容就不能被修改。字符串在内存中以不同的方式存储,具体取决于它是常量字符串还是动态创建的字符串。常量字符串常量字符串在编译时就被解析,并在程序的元数据(Metadata)中存储。多个相同的字符串常量可能会共享同一块内存......
  • 兴达易控EtherCAT主站转Profinet网关带你轻松实现设备互通
    兴达易控EtherCAT主站转Profinet网关带你轻松实现设备互通XD-ETHPNM20是一款EtherCAT主站功能的通讯网关。EtherCAT主站转Profinet网关主要功能是将EtherCAT的从站设备(伺服、阀门、仪表、变频器等)接入到Profinet网络。XD-ETHPNM20网关连接到EtherCAT总线中作为主站使用,连接到Prof......
  • dotnet 8项目Docker部署报错 Unhandled exception. Microsoft.Data.SqlClient.SqlExce
    环境:dotnet8+sqlserver2012本地开发调试正常,部署至Docker容器时,运行实例报错。查看日志显示:Unhandledexception.Microsoft.Data.SqlClient.SqlException(0x80131904):Aconnectionwassuccessfullyestablishedwiththeserver,butthenanerroroccurredduringth......
  • Kubernetes容器实践操作深度解析
    Kubernetes容器实践深度解析引言在当今云原生时代,容器技术已经成为构建、部署和管理应用程序的关键工具之一。而在众多的容器编排系统中,Kubernetes(简称K8s)因其强大的自动化、弹性和可扩展性而备受欢迎。本文将深入探讨Kubernetes容器实践,从基础概念到高级应用,为读者提供全面的指南......
  • [论文阅读] Progressive Domain Expansion Network for Single Domain Generalization
    ProgressiveDomainExpansionNetworkforSingleDomainGeneralization3.Method本文提出的PDEN用于单域泛化。假设源域为\(\mathcal{S}=\left\{x_i,y_i\right\}_{i=1}^{N_S}\),目标域为\(\mathcal{T}=\left\{x_i,y_i\right\}_{i=1}^{N_T}\),其中\(x_i,y_i\)分别表示第......
  • 当network mode设置为host,并指定了-p或-P
    会提示以下警告:WARNING:Publishedportsarediscardedwhenusinghostnetworkmode问题:docker启动时总是遇见以上警告,-p8889:8888的设置也不起任何作用。原因:docker启动时指定--network=host或-net=host,如果还指定了-p或-P,那这个时候就会有此警告,并且通过-p或-P设置的......
  • net8操作appsettings.json类
    1、添回操作类文件AppSettings.csusingMicrosoft.Extensions.Configuration.Json;namespaceYYApi.Helper{///<summary>///appsettings.json操作类///</summary>publicclassAppSettings{publicstaticIConfigurationConfigu......
  • 将.NET Core项目部署到Azure WebJob - Azure SDK
    前提条件已经完成了前四篇文章中的所有步骤。安装了Microsoft.Azure.WebJobs和Microsoft.Azure.WebJobs.Extensions包。创建WebJob在你的项目中,创建一个新的类:SayHelloWebJob。在SayHelloWebJob类中,添加以下代码:usingMicrosoft.Azure.WebJobs;usingSystem;publiccla......
  • 将.NET Core项目部署到Azure WebJob - CRON
    前提条件已经完成了前三篇文章中的所有步骤。学习CRON表达式CRON表达式是一种强大的工具,可以用来描述时间表。你可以使用CRON表达式来配置你的WebJob在特定的时间运行。我推荐你访问这个网站来学习CRON表达式:https://www.baeldung.com/cron-expressions创建settings.job文件......
  • Asp .Net Core 系列:集成 Ocelot+Nacos+Swagger+Cors实现网关、服务注册、服务发现
    目录简介什么是Ocelot?什么是Nacos?什么是Swagger?什么是Cors?Asp.NetCore集成Ocelot网关集成Nacos下游配置Nacos配置跨域(Cors)网关和微服务中配置Swagger效果简介什么是Ocelot?Ocelot是一个开源的ASP.NETCore微服务网关,它提供了API网关所需的所有功能,如路由、......