加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何从ASP.NET Web API方法中查找声明的内容?

发布时间:2020-12-16 07:06:21 所属栏目:asp.Net 来源:网络整理
导读:在我的代码(ASP.NET Identity 2.1)中,我设置如下声明: public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManagerApplicationUserManager();
在我的代码(ASP.NET Identity 2.1)中,我设置如下声明:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
        ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant","The user name or password is incorrect.");
            return;
        }
        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType);
        AuthenticationProperties properties = CreateProperties(
            user.UserName,oAuthIdentity,user.FirstName,user.LastName,user.Organization);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }

这是CreateProperites方法,然后添加了角色声明:

public static AuthenticationProperties CreateProperties(
        string userName,ClaimsIdentity oAuthIdentity,string firstName,string lastName,int organization)
    {

        IDictionary<string,string> data = new Dictionary<string,string>
            {
                { "userName",userName},{ "firstName",firstName},{ "lastName",lastName},{ "organization",organization.ToString()},{ "roles",string.Join(":",oAuthIdentity.Claims.Where(c=> c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray())}

            };
        return new AuthenticationProperties(data);
    }

在我的客户端上,我发出一个令牌请求,然后像这样收到它:

this.$http({
        method: 'POST',url: '/Token',headers: {
            'Content-Type': 'application/x-www-form-urlencoded',},data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),})
        .success((data: any,status,headers,cfg) => {
            self.data.roles = data.roles;

我可以看到self.data.roles正确填充了角色.现在回到服务器上我想查看角色声明的内容.有人可以通过告诉我如何做到这一点来帮忙吗?我知道我可以在一个方法中执行以下操作:

[HttpGet]
    [Route("Retrieve")]
    public async Task<IHttpActionResult> Retrieve()
    {

        var x = User;

x获取的值

System.Security.Claims.ClaimsPrinciple and 
System.Security.Claims.ClaimsIdentity

但在x内我找不到索赔本身的信息.

请注意,我之前尝试过在SO上发布的建议:

var identity = (ClaimsIdentity)User.Identity;
        IEnumerable<Claim> claims = identity.Claims;

        // The following line returns null
        var roles = identity.Claims.Where(r => r.Type == "roles").FirstOrDefault();

但我仍然无法在索赔内找到与角色声明相关的信息.我知道它必须在那里,因为它到达客户端.

请注意我正在寻找具体的“角色”声明.没有任何系统生成的声明.但是我试图添加自己的那个包含角色的连接列表.

解决方法

你试过这个吗?

var roleClaims = identity.Claims.Where(c => c.Type == ClaimTypes.Role);

UPDATE

首先,您没有添加索赔.您正在将一些数据添加到AuthenticationTicket的属性字典中.这些数据恰好是逗号分隔的角色,您选择命名的密钥是“角色”.所以,这不是一个主张.

当你说它对我不起作用时,我相信你想找到你在字典中放入的逗号分隔值.如果是这种情况,则无法从控制器中的用户检索它.当您发送承载令牌时,承载令牌身份验证中间件会读取令牌,从令牌中获取ClaimsIdentity并在上下文中设置该权限,以便您可以将其读取到用户之外.

您在AuthenticationTicket中放置的任何内容都是用于中间件(实际上是处理程序)的.因此,如果您想从AuthenticationTicket获取任何数据,您需要自己在承载中间件上调用AuthenticateAsync.通过执行var result = await AuthenticationManager.AuthenticateAsync(OAuthDefaults.AuthenticationType);,您现在获得整个票证而不仅仅是ClaimsIdentity.通过查看结果,您应该能够获得逗号分隔的角色,但随后了解,承载中间件已经为您完成了一次并且您再次调用它.

顺便说一句,如果要添加自定义声明,则需要将其添加到GrantResourceOwnerCredentials中的oAuthIdentity.

public override async Task GrantResourceOwnerCredentials(
                            OAuthGrantResourceOwnerCredentialsContext context)
{
    // snip
    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
    oAuthIdentity.AddClaim(new Claim("urn:roles","a,b,c");
}

如果你这样做,你可以从用户那里阅读.

var myRoleClaims = identity.Claims.Where(c => c.Type ==“urn:roles”);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读