如何在ASP.NET Identity中添加声明



我正试图找到一个文档或示例,说明如何使用ASP.NET identity在MVC 5中向用户标识添加自定义声明。该示例应显示在OWIN安全管道中插入声明的位置,以及如何使用表单身份验证将声明持久化到cookie中。

假设您使用的是ASP.NET MVC 5项目模板,则添加声明的正确位置位于ApplicationUser.cs中。只需搜索Add custom user claims here。这将引导您使用GenerateUserIdentityAsync方法。当ASP.NET标识系统检索到ApplicationUser对象并需要将其转换为ClaimsIdentity时,会调用此方法。你会看到这行代码:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

之后是评论:

// Add custom user claims here

最后,它返回身份:

return userIdentity;

因此,如果你想添加一个自定义声明,你的GenerateUserIdentityAsync可能看起来像:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));
return userIdentity;

也许下面的文章会有所帮助:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);

如果您想在注册时添加自定义声明,则此代码将起作用:

            var user = new ApplicationUser
            {
                UserName = model.UserName,
                Email = model.Email
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            // Associate the role with the new user 
            await UserManager.AddToRoleAsync(user.Id, model.UserRole);
            // Create customized claim 
            await UserManager.AddClaimAsync(user.Id, new Claim("newCustomClaim", "claimValue"));
            if (result.Succeeded)
            {...etc

您可以在WEB API C#中执行以下操作

var identity = new ClaimsIdentity(context.Options.AuthenticationType);          
        foreach(var Rol in roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
        }
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Email, user.Correo));
        identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Celular));
        identity.AddClaim(new Claim("FullName", user.FullName));
        identity.AddClaim(new Claim("Empresa", user.Empresa));
        identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));

相关内容

  • 没有找到相关文章

最新更新