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

 伍贤厚_197 发布于 2023-02-12 19:25

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

2 个回答
  • 假设您使用的是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;
    

    2023-02-12 19:28 回答
  • 也许以下文章可以提供帮助:

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

    2023-02-12 19:28 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有