GVKun编程网logo

如何使用ASP.NET Identity 2.0允许用户模拟另一个用户?(aspnet账户可以禁用吗)

19

对于想了解如何使用ASP.NETIdentity2.0允许用户模拟另一个用户?的读者,本文将提供新的信息,我们将详细介绍aspnet账户可以禁用吗,并且为您提供关于.netcore3.1+Identi

对于想了解如何使用ASP.NET Identity 2.0允许用户模拟另一个用户?的读者,本文将提供新的信息,我们将详细介绍aspnet账户可以禁用吗,并且为您提供关于.net core3.1 + IdentityServer4-每个用户一个会话、.net – 如何使用Web API 2 AspNet Identity 2扩展IdentityRole、.Net6集成IdentityServer4 +AspNetCore Identity读取数据表用户且鉴权授权管理API、ASP NET Identity 为什么加密规范化的用户名而不是用户名?的有价值信息。

本文目录一览:

如何使用ASP.NET Identity 2.0允许用户模拟另一个用户?(aspnet账户可以禁用吗)

如何使用ASP.NET Identity 2.0允许用户模拟另一个用户?(aspnet账户可以禁用吗)

我正在将ASP.NET MVC 5.1应用程序从MembershipProvider迁移到ASP.NET Identity
v2.0。我在应用程序中拥有的功能之一是用户模拟:管理员可以像在该站点上注册的任何其他用户一样登录,而无需知道密码。

我使用此代码来实现MembershipProvider的用户模拟,并且它不适用于Identity库。

如何在ASP.NET Identity中实现用户模拟(不是IIS模拟)?

答案1

小编典典

我已经找到了解决这个问题的方法。

基本上,我添加了具有管理员用户名的声明,如果该声明存在,我知道正在模拟。当管理员想要停止模拟时,系统会为声明检索原始用户名,删除旧的模拟Cookie并为管理员创建新的Cookie:

[AuthenticateAdmin] // <- make sure this endpoint is only available to adminspublic async Task ImpersonateUserAsync(string userName){    var context = HttpContext.Current;    var originalUsername = context.User.Identity.Name;    var impersonatedUser = await userManager.FindByNameAsync(userName);    var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);    impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));    impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));    var authenticationManager = context.GetOwinContext().Authentication;    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);}

有关更多信息,请参见我的博客文章:使用ASP.Net Identity
2模拟用户。

Asp.Net Core中的用户模拟

2017年7月更新:此主题非常受欢迎,因此我研究了Core中的用户模拟,并且更新的API的原理非常相似。模仿的方法如下:

    [Authorize(Roles = "Admin")] // <-- Make sure only admins can access this     public async Task<IActionResult> ImpersonateUser(String userId)    {        var currentUserId = User.GetUserId();        var impersonatedUser = await _userManager.FindByIdAsync(userId);        var userPrincipal = await _signInManager.CreateUserPrincipalAsync(impersonatedUser);        userPrincipal.Identities.First().AddClaim(new Claim("OriginalUserId", currentUserId));        userPrincipal.Identities.First().AddClaim(new Claim("IsImpersonating", "true"));        // sign out the current user        await _signInManager.SignOutAsync();        // If you use asp.net core 1.0        await HttpContext.Authentication.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);        // If you use asp.net core 2.0 (the line above is deprecated)        await HttpContext.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);        return RedirectToAction("Index", "Home");    }

这是停止模拟的方法:

    [Authorize(Roles = "Admin")] // <-- Make sure only admins can access this     public async Task<IActionResult> StopImpersonation()    {        if (!User.IsImpersonating())        {            throw new Exception("You are not impersonating now. Can''t stop impersonation");        }        var originalUserId = User.FindFirst("OriginalUserId").Value;        var originalUser = await _userManager.FindByIdAsync(originalUserId);        await _signInManager.SignOutAsync();        await _signInManager.SignInAsync(originalUser, isPersistent: true);        return RedirectToAction("Index", "Home");    }

我的博客中有完整说明:http : //tech.trailmax.info/2017/07/user-impersonation-in-asp-net-
core/
GitHub上的完整代码示例:https :
//github.com/trailmax/AspNetCoreImpersonation

.net core3.1 + IdentityServer4-每个用户一个会话

.net core3.1 + IdentityServer4-每个用户一个会话

不确定确切的方案详细信息,例如jwt或参考令牌,任何客户端(前通道或后通道)注销实现。一种可能的通用解决方案:

  • 1分钟的access_token ttl,每3/4分钟刷新一次。
  • // right after await HttpContext.SignInAsync(identityServerUser);
    // in your [HttpPost]Login() action
    await _refreshTokenStore.RemoveAllAsync(new PersistedGrantFilter()
        {ClientId = context.Client.ClientId,SubjectId = user.SubjectId});
    

其中_refreshTokenStore是您注入的IPersistedGrantStore

.net – 如何使用Web API 2 AspNet Identity 2扩展IdentityRole

.net – 如何使用Web API 2 AspNet Identity 2扩展IdentityRole

我试图在最新版本的Visual Studio 2013中扩展Web API 2(带个人帐户)模板中提供的AspNet IdentityRole类.当我点击/ api / roles时,它返回一个空数组

身份模型

namespace API.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class,please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser<string,IdentityUserLogin,ApplicationUserRole,IdentityUserClaim>,IUser,IUser<string>
{
    [NotMapped]
    public virtual UserProfile Profile { get; set; }

    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }

    //public virtual List<ApplicationUserRole> ApplicationRoles { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager,string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationoptions.AuthenticationType
        ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this,authenticationType);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationRole : IdentityRole<string,ApplicationUserRole>
{
    public ApplicationRole() : base() { }

}

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,ApplicationRole,string,IdentityUserClaim> 

{

     public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

     public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

}

身份配置

namespace API
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.

public class ApplicationUserManager : UserManager<ApplicationUser,string>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            requiredLength = 6,RequireNonLetterOrDigit = true,requiredigit = true,RequireLowercase = true,RequireUppercase = true,};
        IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}



public class ApplicationRoleManager : RoleManager<ApplicationRole,string>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole,string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }

}

}

解决方法

你的错误就在这里

ApplicationDbContext : IdentityDbContext<ApplicationUser>

您的数据库上下文是来自IdentityDbContext< ApplicationUser>的范围.
这是基础

IdentityDbContext<TUser,IdentityRole,IdentityUserRole,IdentityUserClaim>

当您希望将ApplicationRole作为您的角色时,ApplicationDbContext将生成IdentityRole.

将ApplicationDbContext更改为

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,IdentityUserClaim>
{

 public ApplicationDbContext()
    : base("DefaultConnection",false)
 {
    base.Configuration.ProxyCreationEnabled = false;
 }

 public static ApplicationDbContext Create()
 {
    return new ApplicationDbContext();
 }
}

你不必在这一点上覆盖OnModelCreating并添加属性Roles.

因为你在ApplicationUserRole中有导航属性,所以你应该添加配置映射

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ApplicationUserRole>().Hasrequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
}

IdentityModel.cs应该是这样的:

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationRole : IdentityRole<string,ApplicationUserRole>
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name,string description)
        : base()
    {
        this.Name = name;
        this.Description = description;
    }

    public string Description { get; set; }
}

public class ApplicationUser : IdentityUser<string,IdentityUserClaim>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,IdentityUserClaim>
{

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUserRole>().Hasrequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
    }
}

identityconfig.cs应该是这样的:

public class ApplicationUserStore : UserStore<ApplicationUser,IUserStore<ApplicationUser>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }   
}

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));
        ....
    }
}
public class ApplicationRoleStore : RoleStore<ApplicationRole,ApplicationUserRole>
{
    public ApplicationRoleStore(ApplicationDbContext context)
        : base(context)
    {

    }
}
public class ApplicationRoleManager : RoleManager<ApplicationRole,IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
        return manager;
    }
}

.Net6集成IdentityServer4 +AspNetCore Identity读取数据表用户且鉴权授权管理API

.Net6集成IdentityServer4 +AspNetCore Identity读取数据表用户且鉴权授权管理API

前言

IdentityServer4 实现鉴权、授权,AspNetCore Identity实现数据库用户管理表直接生成。

ps:IdentityServer4文档上最后给的例子是 // 配置使用内存存储用户信息,但使用 EF 存储客户端和资源信息,

我初步要实现的是 //数据库存储用户信息   内存存储资源   (下一步资源也放数据库  以后弄好了有机会更)

1.创建.Net6 API程序

一顿引用,包括

防止图片挂掉打一遍文字:

  • IdentityServer4、
  • IdengtityServer4.AspNetIdentity、
  • AspNetCore.Identity.EntityFrameWorkCore(生成数据库表用的)、
  • EntityFrameWork+Disign+Tool三件套 (缺了不能自动迁移)、
  • Pomelo.EntityFrameWorkCore.MySql(我是用的MySql,如果是SqlServer 不用这个用一个大概叫EF.Sqlserver的)、
  • Encrypt (加密MD5用的 不必须)、

下面那个是自带的。

2.建立数据库连接类

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MyIDP;
using MyIDP.Models;
using MyIDP.Permission;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//由此重要
builder.Services.AddDbContext<IdpDbContext>(opt =>
{
    opt.UseMySql("server=127.0.0.1;Port=3306;database=AccountDb;uid=root;pwd=123456;", new MySqlServerVersion(new Version(8,0,29)));
});

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddUserManager<MyUserManager>()
                .AddEntityFrameworkStores<IdpDbContext>()
                .AddDefaultTokenProviders();

builder.Services.AddIdentityServer()
    .AddDeveloperSigningCredential()

    .AddInMemoryIdentityResources(MyIDP.IdpConfig.GetIdentityResources())
    .AddInMemoryClients(MyIDP.IdpConfig.GetClients())
    .AddInMemoryApiScopes( MyIDP.IdpConfig.GetScope())
    .AddInMemoryApiResources( MyIDP.IdpConfig.GetApiResources())    //.AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() //这句可以打开自主验证登录用户
    //.AddProfileService<MyProfileService>()
    .AddAspNetIdentity<ApplicationUser>()
    //.AddTestUsers(new List<IdentityServer4.Test.TestUser>
    //{
    //    new IdentityServer4.Test.TestUser
    //    {
    //        SubjectId="123",
    //        Username = "alice",
    //        Password = "alice",
    //        Claims = new List<Claim>() {
    //            new Claim(JwtClaimTypes.Role, "superadmin"),
    //            new Claim(JwtClaimTypes.Role, "admin")
    //        }
    //    }
    //})
    ;

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseIdentityServer();
app.UseAuthorization();
app.MapControllers();
app.Run();

3.Program里开始加东西(如果是历史的Net版本,是在StartUp里)

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MyIDP;
using MyIDP.Models;
using MyIDP.Permission;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//由此重要
builder.Services.AddDbContext<IdpDbContext>(opt =>
{
    opt.UseMySql("server=127.0.0.1;Port=3306;database=AccountDb;uid=root;pwd=123456;", new MySqlServerVersion(new Version(8,0,29)));
});
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddUserManager<MyUserManager>()
                .AddEntityFrameworkStores<IdpDbContext>()
                .AddDefaultTokenProviders();
builder.Services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    .AddInMemoryIdentityResources(MyIDP.IdpConfig.GetIdentityResources())
    .AddInMemoryClients(MyIDP.IdpConfig.GetClients())
    .AddInMemoryApiScopes( MyIDP.IdpConfig.GetScope())
    .AddInMemoryApiResources( MyIDP.IdpConfig.GetApiResources())    //.AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() //这句可以打开自主验证登录用户
    //.AddProfileService<MyProfileService>()
    .AddAspNetIdentity<ApplicationUser>()
    //.AddTestUsers(new List<IdentityServer4.Test.TestUser>
    //{
    //    new IdentityServer4.Test.TestUser
    //    {
    //        SubjectId="123",
    //        Username = "alice",
    //        Password = "alice",
    //        Claims = new List<Claim>() {
    //            new Claim(JwtClaimTypes.Role, "superadmin"),
    //            new Claim(JwtClaimTypes.Role, "admin")
    //        }
    //    }
    //})
    ;
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseIdentityServer();
app.UseAuthorization();
app.MapControllers();
app.Run();

因为使用的是内存储存t鉴权信息的方式,所以建立IdentityServer4的配置类IdpConfig

public static class IdpConfig
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Address(),
                new IdentityResources.Phone(),
                new IdentityResources.Email()
            };
        }
        public static IEnumerable<ApiResource> GetApiResources()
        {
            //return new ApiResource[]
            //{
            //    new ApiResource("api1", "My API #1",new List<string>(){JwtClaimTypes.Role})
            //};
            //新写法
            return new[]
            {
                new ApiResource("api1", "My API #1")
                {
                    Scopes = { "scope1"}
                }
            };
        }
        public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                #region MyRegion
                 //// client credentials flow client
                //new Client
                //{
                //    ClientId = "console client",
                //    ClientName = "Client Credentials Client",

                //    AllowedGrantTypes = GrantTypes.ClientCredentials,

                //    ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },

                //    AllowedScopes = { "api1" }
                //},

    #endregion
                // wpf client, password grant
                new Client
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = //允许当访问的资源
                    {
                        "scope1",
                        //"api1",
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Email,
                        IdentityServerConstants.StandardScopes.Address,
                        IdentityServerConstants.StandardScopes.Phone,
                        IdentityServerConstants.StandardScopes.Profile }
                }
            };
        }
        public static IEnumerable<ApiScope> GetScope()
        {
            return new ApiScope[] {
                new ApiScope("scope1"),
                new ApiScope("scope2"),
            };
        }
    }

数据库的usernamager

public class MyUserManager : UserManager<ApplicationUser>
    {
        public MyUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher,
          IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
           : base(store, optionsAccessor, new MyPasswordHasher(), userValidators, passwordValidators, keyNormalizer, errors, services, logger)
        {
            optionsAccessor.Value.Password.RequireDigit = false;
            optionsAccessor.Value.Password.RequiredLength = 4;
            optionsAccessor.Value.Password.RequireLowercase = false;
            optionsAccessor.Value.Password.RequireUppercase = false;
            optionsAccessor.Value.Password.RequireNonAlphanumeric = false;
        }

    }

重写验证密码的方法类MyResourceOwnerPasswordValidator,(如果没有打开Program中的AddResourceOwnerValidator<MyResourceOwnerPasswordValidator>() 则不需要)

public class MyResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        public readonly SignInManager<ApplicationUser> signInManager;
        private readonly MyUserManager userManager;
        //public readonly IEventService service;
        public MyResourceOwnerPasswordValidator(MyUserManager userService, SignInManager<ApplicationUser> signInManager)//, IEventService service)
        {
            userManager = userService;
            this.signInManager = signInManager;
            //this.service = service;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password))
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "验证被拒绝,用户名或者密码为空。");
                return;
            }
            var user = await userManager.FindByNameAsync(context.UserName);
            if (user == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "验证失败,不存在当前用户。");
                return;
            }
            //检验用户密码(虽然我也不知道他的密码是采用什么加密方式得到的,但是我也不需要知道) 
            var passwordPass = await userManager.CheckPasswordAsync(user, context.Password);
            if (!passwordPass)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "验证失败,用户凭证错误");
                return;
            }
            else
            {
                try
                {
                    await userManager.AddLoginAsync(user, new UserLoginInfo(user.Id, "", user.UserName));
                }
                catch (Exception ex)
                {
                    ;
                }
                finally
                {
                    context.Result = new GrantValidationResult(user.Id, GrantType.ResourceOwnerPassword, new List<Claim>() { new Claim("account", user.UserName) }); 
                }
            }
            return;
        }
    }

MyPasswordHasher

public class MyPasswordHasher : PasswordHasher<ApplicationUser>
    {
        public override string HashPassword(ApplicationUser user, string password)
        {
            //PasswordHasher<ApplicationUser> ph = new PasswordHasher<ApplicationUser>();
            //var pstr = ph.HashPassword(new ApplicationUser(), password);
            //return pstr;
            return password.MD5();
        }

        public override PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword)
        {
            if (providedPassword.MD5().Equals(hashedPassword))
            {
                return PasswordVerificationResult.Success;
            }
            else
            {
                return PasswordVerificationResult.Failed;
            }
        }
    }

创建自己的User类 ApplicationUser继承 IdentityUser  复写自带的AspNetUser表

public class ApplicationUser : IdentityUser
    {
        public string MySomething { get; set; } = "";
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// 创建人Id
        /// </summary>
        public string CreatorId { get; set; } = "";
        /// <summary>
        /// 否已删除
        /// </summary>
        public bool Deleted { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string RealName { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public Sex Sex { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime? Birthday { get; set; }
        /// <summary>
        /// 所属部门Id
        /// </summary>
        public string DepartmentId { get; set; } = "";
        public string OtherData { get; set; } = "";
        // 用户角色 用户权限 用户信息 用户登录tokens  重新绑定与父类的关系 命名必须和父类一致
        public virtual ICollection<IdentityUserRole<string>> UserRoles { get; set; }
        public virtual ICollection<IdentityUserClaim<string>> Claims { get; set; }
        public virtual ICollection<IdentityUserLogin<string>> Logins { get; set; }
        public virtual ICollection<IdentityUserToken<string>> Tokens { get; set; }
    }
    public enum Sex
    {
        [Description("男")]
        Man = 1,
        [Description("女")]
        Woman = 0
    }

至此可以生成数据库迁移后 Postman测试一下:

到此这篇关于.Net6集成IdentityServer4 +AspNetCore Identity读取数据表用户且鉴权授权管理API的文章就介绍到这了,更多相关.Net6 读取数据表用户内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • 关于.NET6 Minimal API的使用方式详解
  • 使用.Net6中的WebApplication打造最小API
  • 使用.NET6实现动态API
  • .NET6在WebApi中使用日志组件log4net
  • .NET6自定义WebAPI过滤器
  • .NET6使WebApi获取访问者IP地址

ASP NET Identity 为什么加密规范化的用户名而不是用户名?

ASP NET Identity 为什么加密规范化的用户名而不是用户名?

如何解决ASP NET Identity 为什么加密规范化的用户名而不是用户名??

正如我在默认 UserManager 实现中注意到的那样具有 ProtectPersonalData 标志并且它为 normalizedUserNamenormalizedEmail 启用加密,但它不适用于非规范化对,如 UserName 和电子邮件和考虑这些值是相同的(除了规范化)有没有加密数据的意义?,即便如此,即使我们可以在两个不同的层中从两个地方进行加密也有同样的担忧用户经理?作为一种解决方法,我可以覆盖默认类,但我想了解这些背后的原因

用于设置和更新 normalizedUserName 的代码

    public virtual async Task UpdatenormalizedUserNameAsync(TUser user)
    {
        var normalizedname = normalizeName(await GetUserNameAsync(user));
        normalizedname = ProtectPersonalData(normalizedname);
        await Store.SetnormalizedUserNameAsync(user,normalizedname,CancellationToken);
    }

设置和更新用户名的代码

    public virtual async Task<IdentityResult> SetUserNameAsync(TUser user,string userName)
    {
        ThrowIfdisposed();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        await Store.SetUserNameAsync(user,userName,CancellationToken);
        await UpdateSecurityStampInternal(user);
        return await UpdateUserAsync(user);
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

今天关于如何使用ASP.NET Identity 2.0允许用户模拟另一个用户?aspnet账户可以禁用吗的讲解已经结束,谢谢您的阅读,如果想了解更多关于.net core3.1 + IdentityServer4-每个用户一个会话、.net – 如何使用Web API 2 AspNet Identity 2扩展IdentityRole、.Net6集成IdentityServer4 +AspNetCore Identity读取数据表用户且鉴权授权管理API、ASP NET Identity 为什么加密规范化的用户名而不是用户名?的相关知识,请在本站搜索。

本文标签: