如何在 JWT 令牌中包含声明?
How to include claims in JWT token?
您好,我正在 .Net 核心中开发 Web 应用程序。我已经实施了 V2 身份验证。现在我需要添加授权。要求指出,首先,
It should not be the job of the application to gather the claims of
the user, they should be available in the users JWT. Second,
Permissions with an application will be granted based on claims.
下面是我的验证码。
services
.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = azureActiveDirectoryOptions.Authority;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new List<string>
{
azureActiveDirectoryOptions.AppIdUri,
azureActiveDirectoryOptions.ClientId
},
};
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
有人可以帮我添加基于声明的授权吗?任何帮助将不胜感激。谢谢
您可以使用如下代码在 JWT 令牌中添加自定义声明。
public string createToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", "joey"),
new Claim("Email","xxx@test.com")
});
const string sec = "yoursecurityKey";
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var jwtSecurityToken = handler.CreateJwtSecurityToken(
"issuer",
"Audience",
new ClaimsIdentity(claimsIdentity),
DateTime.Now,
DateTime.Now.AddHours(1),
DateTime.Now,
signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
更多细节,你可以参考这个article。
更新:
如果是这样,您可以使用 JwtBearerEvents 添加声明。
.AddJwtBearer(o =>
{
//Additional config snipped
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
//Get the calling app client id that came from the token produced by Azure AD
string clientId = ctx.Principal.FindFirstValue("appid");
var claims = new List<Claim>
{
new Claim("UserName", "joey")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
};
});
对于授权部分,您可以add app roles in your application,将角色分配给users/groups,以便roles
在用户登录并同意后包含在token中,您的应用程序可以使用策略来限制访问权限基于 roles
声明。
另一种方法是 use Azure AD Groups and Group Claims 。不同之处在于您的应用程序应检查 groups
声明,
您好,我正在 .Net 核心中开发 Web 应用程序。我已经实施了 V2 身份验证。现在我需要添加授权。要求指出,首先,
It should not be the job of the application to gather the claims of the user, they should be available in the users JWT. Second, Permissions with an application will be granted based on claims.
下面是我的验证码。
services
.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = azureActiveDirectoryOptions.Authority;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new List<string>
{
azureActiveDirectoryOptions.AppIdUri,
azureActiveDirectoryOptions.ClientId
},
};
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
有人可以帮我添加基于声明的授权吗?任何帮助将不胜感激。谢谢
您可以使用如下代码在 JWT 令牌中添加自定义声明。
public string createToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim("UserName", "joey"),
new Claim("Email","xxx@test.com")
});
const string sec = "yoursecurityKey";
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var jwtSecurityToken = handler.CreateJwtSecurityToken(
"issuer",
"Audience",
new ClaimsIdentity(claimsIdentity),
DateTime.Now,
DateTime.Now.AddHours(1),
DateTime.Now,
signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
更多细节,你可以参考这个article。
更新:
如果是这样,您可以使用 JwtBearerEvents 添加声明。
.AddJwtBearer(o =>
{
//Additional config snipped
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
//Get the calling app client id that came from the token produced by Azure AD
string clientId = ctx.Principal.FindFirstValue("appid");
var claims = new List<Claim>
{
new Claim("UserName", "joey")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
};
});
对于授权部分,您可以add app roles in your application,将角色分配给users/groups,以便roles
在用户登录并同意后包含在token中,您的应用程序可以使用策略来限制访问权限基于 roles
声明。
另一种方法是 use Azure AD Groups and Group Claims 。不同之处在于您的应用程序应检查 groups
声明,