如何在ASP.NET标识中添加声明

时间:2013-12-04 19:16:23

标签: asp.net-mvc-5 asp.net-identity

我正在尝试查找如何使用ASP.NET标识在MVC 5中向用户标识添加自定义声明的文档或示例。该示例应显示在OWIN安全管道中插入声明的位置以及如何使用表单身份验证将它们保存在cookie中。

4 个答案:

答案 0 :(得分:59)

假设您正在使用ASP.NET MVC 5项目模板,添加声明的正确位置在ApplicationUser.cs中。只需搜索Add custom user claims here即可。这将引导您使用GenerateUserIdentityAsync方法。这是在ASP.NET Identity系统检索到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;

答案 1 :(得分:38)

也许following article可以提供帮助:

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);

答案 2 :(得分:4)

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

            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

答案 3 :(得分:2)

您可以在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));

....