我正在尝试学习 JWT 和 ouath。我遇到了 JWT 的形式,它可以帮助我开发我的授权服务器。
我遇到的格式如下:
{
iat: 1416929061,
jti: "802057ff9b5b4eb7fbb8856b6eb2cc5b",
scopes: {
users: {
actions: ['read', 'create']
},
users_app_metadata: {
actions: ['read', 'create']
}
}
}
然而,由于在添加声明时我们只能添加简单的字符串,如何实现这样的事情呢?
到目前为止我看到的唯一方法是使用 JSON.serialization - 来自 https://stackoverflow.com/a/27279400/2476347
new Claim(someClass,JsonConvert.SerializeObject(result)
任何指南将不胜感激!谢谢!
用于测试的代码
我想在 JWT 中使用的类
public class MyTes
{
public string area { get; set; }
public List<string> areapermissions { get; set; }
}
然后我使用以下代码生成 token
var identity = new ClaimsIdentity("JWT");
var cos = new List<string>();
cos.Add("aaa");
cos.Add("bbb");
MyTes vario = new MyTes()
{
area = "someregion",
areapermissions = cos
};
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));
identity.AddClaim(new Claim("scope", "xyz1"));
identity.AddClaim(new Claim("scope", "xyz2"));
identity.AddClaim(new Claim("scope", "xyz3"));
identity.AddClaim(new Claim("APIs", JsonConvert.SerializeObject(cos)));
identity.AddClaim(new Claim("APIs2", JsonConvert.SerializeObject(vario)));
这没有错误,当我解码我现在得到的票时:
{
"unique_name": "Rafski",
"sub": "Rafski",
"role": [
"Manager",
"Supervisor"
],
"scope": [
"xyz1",
"xyz2",
"xyz3"
],
"APIs": "[\"aaa\",\"bbb\"]",
"APIs2": "{\"area\":\"someregion\",\"areapermissions\":[\"aaa\",\"bbb\"]}",
"iss": "http://kurwa.mac",
"aud": "7aaa70ed8f0b4807a01596e2abfbd44d",
"exp": 1429351056,
"nbf": 1429349256
}
最佳答案
以下是如何使用 .Net 创建具有复杂 JSON 声明的 JWT token 。
使用Nuget获取库:System.IdentityModel.Tokens.Jwt
然后使用以下代码创建 JWT token 。
var keybytes = Convert.FromBase64String(YOUR_CLIENT_SECRET);
var signingCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(keybytes),
SecurityAlgorithms.HmacSha256Signature,
SecurityAlgorithms.Sha256Digest);
var nbf = DateTime.UtcNow.AddSeconds(-1);
var exp = DateTime.UtcNow.AddSeconds(120);
var payload = new JwtPayload(null, "", new List<Claim>(), nbf, exp);
var users = new Dictionary<string, object>();
users.Add("actions", new List<string>() { "read", "create" });
var scopes = new Dictionary<string, object>();
scopes.Add("users", users);
payload.Add("scopes", scopes);
var jwtToken = new JwtSecurityToken(new JwtHeader(signingCredentials), payload);
var jwtTokenHandler = new JwtSecurityTokenHandler();
return jwtTokenHandler.WriteToken(jwtToken);
这会产生一个 token ,例如
{
"typ": "JWT",
"alg": "HS256"
}
{
"exp": 1433254394,
"nbf": 1433254273,
"scopes": {
"users": {
"actions": [
"read", "create"
]
}
}
}
关于c# - 带有 OWIN 的 webapi 中的复杂 JSON Web token 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715178/