我正在使用我自己的oauth authtentication系统并希望使用JWT令牌。 ms实现有点令人困惑。我在网上看到以下哈希算法
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"];
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
return jwt;
}
但似乎无法找出如何从令牌中提取用户信息
答案 0 :(得分:0)
您所展示的是JWT保护实施,它不是开箱即用的。这是用于序列化和加密令牌而不是对话。如果您已经管理了那部分(那是一个困难的部分),那么从JWT令牌中读取用户声明应该很容易。这通常由Microsoft.Owin.Security.Jwt
中间件
var issuer = "http://myidentityserverurl.com"
var audience = ConfigurationManager.AppSettings["as:AudienceId"];
var symmetricKey = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = "JWT",
AllowedAudiences = new string[] { audience } ,
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, symmetricKey)
}
});
查看此github repo以及随附的文章here,了解完整的示例端到端。