代码之家  ›  专栏  ›  技术社区  ›  Arnaud F.

ASP。NET Core-向用户添加角色声明

  •  24
  • Arnaud F.  · 技术社区  · 7 年前

    我读了很多关于OWIN/Cookie/UserManager/UserStore/Identity等等的东西,我都迷路了。

    问题:如何以最简单的方式为整个应用程序的当前登录用户(windows)添加角色声明?

    [Authorize(Role= "MyAddedRole")] bool res = User.IsInRole("MyAddedRole")

    谢谢

    3 回复  |  直到 7 年前
        1
  •  18
  •   ashk hp    6 年前

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, UserName),
        new Claim(ClaimTypes.Role, "User"),
        new Claim(ClaimTypes.Role, "Admin"),
        new Claim(ClaimTypes.Role, Watever)
    };
    

    [Authorize(Roles = "Watever")]
    

    User.IsInRole("Watever")
    
        2
  •  17
  •   Arnaud F.    7 年前

    回答我自己,那么我做了什么:

    创建我自己的UserClaimStore(我只需要这个商店,不需要其他商店):

    public class MyIdentityStore :
        IUserClaimStore<IdentityUser>
    {
        private MyDbContext _myDbContext;
        private bool _disposed = false; 
    
        public MyIdentityStore(MyDbContext myDbContext)
        {
            _myDbContext = myDbContext;
        }
    
        #region IUserClaimStore
        public Task<IList<Claim>> GetClaimsAsync(IdentityUser user, CancellationToken cancellationToken)
        {
            // logic here to retrieve claims from my own database using _myDbContext
        }
    
        // All other methods from interface throwing System.NotSupportedException.
        #endregion
    
        #region IDisposable Support
    
        protected virtual void Dispose(bool disposing)
        { /* do cleanup */ }
        #endregion
    }
    

    然后创建了我自己的ClaimTransformer:

    public class MyClaimsTransformer : IClaimsTransformer
    {
        private UserManager<IdentityUser> _userManager;
    
        public MyClaimsTransformer(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }
    
        public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
        {
            var identity = ((ClaimsIdentity)context.Principal.Identity);
    
            // Accessing the UserClaimStore described above
            var claims = await _userManager.GetClaimsAsync(new IdentityUser(identity.Name));
            identity.AddClaims(claims);
    
            return await Task.FromResult(context.Principal);
        }
    }
    

    最后,在启动中。反恐精英:

        public void ConfigureServices(IServiceCollection services)
        {
            /* All other stuff here */ 
    
            // Adding Database connection
            services.AddDbContext<MyDbContext>(o => /* my options */);
    
            // Associates our database and store to identity
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<MyDbContext>()
                .AddUserStore<MyIdentityStore>();
    
            // Claims transformation from database to claims
            services.AddTransient<IClaimsTransformer, MyClaimsTransformer>();
        }
    
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            /* All other stuff here */ 
    
            app.UseIdentity();
    
            app.UseClaimsTransformation(async (context) =>
            { // Retrieve user claims from database
                IClaimsTransformer transformer = context.Context.RequestServices.GetRequiredService<IClaimsTransformer>();
                return await transformer.TransformAsync(context);
            });
        }
    

    现在我可以自由使用 [Authorize(Roles = "MyRole")] User.IsInRole("MyRole") 甚至 User.HasClaim(/* */)

        3
  •  4
  •   Mladen B.    5 年前

    A. User 你说的对象有多个 Identities ,都可以有多个 Claims

    另一种可能更简单的方法是创建一个新的标识对象(包含所有附加声明),并使用 AddIdentity() method .

    User.Claims 该枚举将返回用户对象上所有身份的所有声明。

    var myIdentity = new ClaimsIdentity(new []
    {
        new Claim("claim type", "claim value"), 
        new Claim("claim type", "claim value"), 
        new Claim("claim type", "claim value"), 
    });
    
    context.User.AddIdentity(myIdentity);
    

    使用者声称 将返回用户对象上的所有原始声明以及您的其他声明。