C# 修改身份或添加声明

2024-03-23

应用程序是 Blazor Server .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;
            }
        )

在我看来,这应该迫使程序的智能感知在寻找身份时理解 ApplicationUser 是默认类。

但是,当我尝试打电话时:

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

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

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

另外,如果这是完全错误的,我应该用索赔来做到这一点吗?如果是这样,我无法找到有效使用 Blazor Server 声明的具体方法。


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

在包管理器控制台中执行:

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

将值插入到在 Users 表中创建的 FirstName 和 LastName

创建一个名为:ApplicationUserClaimsTransformation 的类

ApplicationUser ClaimsTransformation.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>();

索引剃刀

@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 名称更改为 ApplicationUser Startup 类、LogOut.cshtml 文件、_LoginPartial.cshtml 文件和 在ApplicationDbContext类的定义中:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 修改身份或添加声明 的相关文章

随机推荐

  • 将数据表从一个数据集复制到另一个数据集

    我正在尝试将位于不同数据集 Y 内部的数据表添加到新的数据集 X 如果直接添加的话 会出现以下错误 DataTable 已属于另一个 DataSet 我是否必须克隆 DataTable 并将所有行导入其中 然后将新的 DataTable 添
  • 动画径向渐变CSS3:从左到右移动? [复制]

    这个问题在这里已经有答案了 我想要一个带有径向渐变的动画背景radial gradient circle rgba 255 255 255 0 8 0 rgba 255 255 255 0 100 将其从左向右移动 http jsfiddl
  • Magento 多个 Authorize.net 网关

    我见过这个关于货币类型的问题 但我要问的是如何在同一商店为不同的信用卡类型配置第二个 Authorize net 帐户 因此 我们希望一些信用卡使用第一个主 Authorize net 网关 而其他信用卡使用辅助 Authorize net
  • Background.js 找不到使用内容脚本注入的内容

    我的 Chrome 扩展有一个内容脚本 可以将自定义 DIV 注入当前页面 这部分有效 但是 该扩展还有一个右键单击上下文菜单 单击该菜单时 应该以某种方式修改此注入的 DIV 比方说 向该 DIV 添加一些文本 问题是找不到注入的内容 右
  • 尝试在Python中导入docx

    公平警告 我对 python 非常陌生 所以请原谅我犯的任何愚蠢错误 我希望能够使用 Python 在 Mac 上打开 关闭 操作 读取 Word 文档 docx 文件 python docx 模块看起来非常有用 所以我一直尝试将其安装在我
  • 如何在组织模式下取消选中下一个循环/重复任务的复选框

    对于组织模式下的循环或重复任务 在该任务内 如果有多个复选框且全部标记为勾选 则在一般任务屏蔽为 完成 后 下一个循环周期的复选框仍显示为勾选 并且应该取消勾选 例如 TODO Cyclic monthly home 0 5 SCHEDUL
  • Node.js - 部署 Node.js 应用程序时是否需要在生产服务器上重新安装所有模块

    我已经开发了我的第一个 Node js pp 目前 它只是放在我的笔记本电脑上 在开发过程中我必须安装一些模块 npm install socket io npm install email protected cdn cgi l emai
  • Angular 1 项目的 TSLint 配置

    我的团队正在使用 Angular 1 5 typescript 进行项目 有人可以给我关于像我这样的项目的最佳 TSLint 配置的建议吗 我现在想添加 TSLint 配置 https github com Microsoft TypeSc
  • 如何在数据坐标中的绘图之外编写注释

    我的图形来自y 1 to y 10 我想在任意位置写一小段文字 比如x 2000 y 5 ax annotate MgII xy 2000 0 5 0 xycoords data 现在我想要相同的 但这次文本必须位于图形之外 但位于我在数据
  • 聊天框,自动滚动到底部

    如何让聊天框自动滚动 HTML
  • IndexedDB - 什么是 Key、keyPath 和 indexName?

    我来自MySQL 习惯了传统的数据库表方案 我无法理解 IndexedDB 及其一些术语 我在文档中查找了这些定义 Key一种数据值 通过它在对象存储中组织和检索存储的值 索引名称要创建的索引的名称 keyPath要使用的索引的键路径 基本
  • 使用构建器和 MapStruct 将 null 值映射到默认值

    我想映射字段Source to Target类 如果源值为null 我想根据数据类型将其转换为默认值 表示字符串 0表示数字类型等 为了设置值 我没有使用常规设置器 而是使用构建器 带有protobuf https developers g
  • HTML 5 页面转换

    我想在页面之间进行漂亮 现代的过渡 我找到了这个教程 http www onextrapixel com 2010 02 23 how to use jquery to make slick page transitions http ww
  • 条形码(Code 128)字体有问题无法扫描

    很容易生成一个3 of 9 http www squaregear net fonts free3of9 shtml条形码使用Font Font f new Font Free 3 of 9 80 this Font f Label l n
  • 参数数量变化的多项式函数

    是否有可能 在Python中 定义参数数量不断变化的多项式类型的函数 参数的数量应该根据我的输入文件中的数据系列的数量而变化 目前我有这样的事情 def y x a0 x2 x3 x4 y a0 a1 x a2 x 2 a3 x 3 ret
  • 我怎样才能在 bouncyCastle 中做到这一点(获取安装的证书)?

    好吧 我对 bouncyCastle 的加密世界还很陌生 也许是一个心理障碍 我似乎找不到 google for 相当于 X509Store store new X509Store StoreName My StoreLocation Cu
  • 有没有更快的方法在 OpenCV 中应用亮度?

    在我的应用程序中 我有以下代码 它将像素的亮度更改 20 for int y 0 y lt src rows y for int x 0 x lt src cols x for int c 0 c lt 3 c src at
  • Typescript:如何在 React 组件中设置子项的类型?

    我可以在 TypeScript 中设置子项的类型吗 例如我有这样的组件 class UserProfile extends React Component lt id number void gt class Thumbnail exten
  • 道场:道场 onblur 事件

    我有一个 dojo 1 5 的表单设置 我正在使用 dijit form ComboBox 和 dijit form TextBox 组合框具有 汽车 自行车 摩托车 等值 文本框是组合框的形容词 因此 组合框中的内容并不重要 但如果组合框
  • C# 修改身份或添加声明

    应用程序是 Blazor Server NET Core 5 0 我正在使用 NET Core 的身份系统 但遇到了问题 我希望将这个人的名字与身份一起存储 以便我可以轻松地调用它 目前我有一个类覆盖基本身份 public class Ap