Add a claim to JWT as an array?

后端 未结 4 1040
醉话见心
醉话见心 2021-01-01 17:52

Using thinktecture JWT authentication resource owner flow,i use the claims part of JWT for client consumption. My question is that if its possible to add claim in identity s

4条回答
  •  时光取名叫无心
    2021-01-01 18:12

    I was having a similar issue, in my case I have claims that are arrays but sometimes only have one item depending on user permissions. In that case if you use new Claim("key", "value") to add them they will be strings when there is a single object and arrays when > 1 which was unacceptable.

    A better solution in this case is to use JwtPayload to build the JwtSecurityToken object.

    var payload = new JwtPayload
        {
            { "ver", version },
            { "iss", "example.com"},
            { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds()},
            { "exp", DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds()},
            { "aud", myExampleStringList }
        };
    var token = new JwtSecurityToken(new JwtHeader(_signingCredentials), payload);
    

    This works on .netcore 3.0 using System.IdentityModel.Tokens.Jwt v3.0 but I can't confirm for other versions.

提交回复
热议问题