【发布时间】:2021-12-07 22:17:04
【问题描述】:
我是 Azure AD 的新手。我们正在使用 v1.0 令牌。我有一个 Azure JWT 令牌验证例程,主要基于 ValidateSignature 和 AzureTokenValidation 以下是我的 ClaimsTransformer:
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
<do something>
var token = httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (Validate(token))
{
<proceed to add claims>
}
和我的验证程序:
public bool Validate(string token)
{
string stsEndpoint = "https://login.microsoftonline.com/common/.well-known/openid-configuration";
ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsEndpoint, new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
TokenValidationParameters parameters = new TokenValidationParameters
{
ValidIssuer = "https://sts.windows.net/<mytenant-id>",
ValidAudience = <my client-id>,
IssuerSigningKeys = config.SigningKeys,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
};
JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
SecurityToken jwt;
bool verified;
try
{
var handler = tokendHandler.ValidateToken(token, validationParameters, out jwt);
var signature = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)jwt).RawSignature;
string algorithm = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)jwt).Header["alg"].ToString();
if (signature.Length == 0 || algorithm.ToLower().Equals("none"))
{
tokenVerified = false;
}
tokenVerified = true;
}
catch
{
tokenVerified = false;
}
return tokenVerified;
}
请告诉我我做的是否正确,或者我可以使用(在我的验证(字符串令牌)中)
try
{
var result = tokendHandler.ValidateToken(token, validationParameters, out _);
verified = true;
}
catch {
verified = false;
}
并且是,检查算法(不接受 alg 中的“无”)和签名存在是必需的,或者这种检查方式是否正确?没有“秘钥”
【问题讨论】:
-
您没有在应用程序中实施标准 Azure AD JWT 身份验证的任何原因?为什么要编写手动验证?
-
你好,没有理由,因为我是新手,我不知道是否存在。有没有套路?还是我遗漏了一些明显的东西(大多数情况下我可能不知道)。你能帮忙吗?
-
这是构建受 Azure AD JWT 保护的 API 的官方示例:github.com/Azure-Samples/…
标签: azure-active-directory jwt