如何手动验证Microsoft登录提供商发出的JWT访问令牌



我有一个Angular应用程序,让用户使用Microsoft和Google帐户登录。登录步骤结束后,我得到了一个访问令牌,该令牌被发送到API进行验证,以确保应用程序的安全。API是ASP.net核心6应用程序。

我用下面的代码成功验证了谷歌发出的访问令牌。但是,我需要对微软发布的访问令牌做同样的事情。

builder.Services.AddAuthentication(x =>
{
x.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultSignOutScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SecurityTokenValidators.Add(new MicrosoftTokenValidator()); // todo
options.SecurityTokenValidators.Add(new GoogleTokenValidator());
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appSettings.AccessTokenSecretKey)),
ValidateIssuer = false,
ValidateAudience = false,
ValidIssuer = appSettings.AccessTokenValidIssuer,
ValidAudience = appSettings.AccessTokenValidAudience
};
});

使用谷歌,使用GoogleJsonWebSignature.ValideAsync使用Google.Apis.Auth

public class GoogleTokenValidator : ISecurityTokenValidator
{
private readonly JwtSecurityTokenHandler _tokenHandler;
public GoogleTokenValidator()
{
_tokenHandler = new JwtSecurityTokenHandler();
}
public bool CanValidateToken => true;
public int MaximumTokenSizeInBytes { get; set; } = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;
public bool CanReadToken(string securityToken)
{
return _tokenHandler.CanReadToken(securityToken);
}
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
validatedToken = null;
var payload = GoogleJsonWebSignature.ValidateAsync(securityToken, new GoogleJsonWebSignature.ValidationSettings()).Result; // here is where I delegate to Google to validate
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, payload.Name),
new Claim(ClaimTypes.Name, payload.Name),
new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName),
new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName),
new Claim(JwtRegisteredClaimNames.Email, payload.Email),
new Claim(JwtRegisteredClaimNames.Sub, payload.Subject),
new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer),
};
try
{
var principle = new ClaimsPrincipal();
principle.AddIdentity(new ClaimsIdentity(claims, "Password"));
return principle;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}

我试图为Microsoft Provider找到相同的验证模式,但没有成功。这就是为什么我要求SO社区得到一些答案或帮助。

我找到了Microsoft Graph API和Azure Identity,但它没有给我任何线索。

我找到了问题的答案。昨天,我在想微软本可以做一些类似GoogleJsonWebSignature的事情,但我试图找到它。这是一个错误!

我意识到我可以用System.IdentityModel.Tokens.Jwt解码每个访问令牌https://jwt.io/libraries.

然后,我可以在public ClaimsPrincipal ValidateToken方法中以这种方式读取令牌,然后编写我的验证逻辑:

var token = new JwtSecurityToken(securityToken);

最新更新