我希望这可以帮助某人,即使帖子有点旧了。
我找到了答案,不是在谷歌搜索后,而是 Binging !我的灵感来自this official code。
您可以使用 JwtBearerOptions 的魔力编写自己的类来非常简单地处理授权。这个类(希望)包含您自己验证 JWT 所需的一切。
因此,您必须将其作为服务注入,并使用它来配置您的身份验证。在你的Startup.ConfigureServices 里有类似的东西:
this.JwtOptions = new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = yourTokenValidationParameters
};
services.AddSingleton<JwtBearerOptions>(this.JwtOptions);
然后,您必须创建一个用于验证您的令牌 (This is where my code was inspired) 的类。我们称它为支持者,因为他支持你!:
public class JwtBearerBacker
{
public JwtBearerOptions Options { get; private set; }
public JwtBearerBacker(JwtBearerOptions options)
{
this.Options = options;
}
public bool IsJwtValid(string token)
{
List<Exception> validationFailures = null;
SecurityToken validatedToken;
foreach (var validator in Options.SecurityTokenValidators)
{
if (validator.CanReadToken(token))
{
ClaimsPrincipal principal;
try
{
principal = validator.ValidateToken(token, Options.TokenValidationParameters, out validatedToken);
}
catch (Exception ex)
{
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
&& ex is SecurityTokenSignatureKeyNotFoundException)
{
Options.ConfigurationManager.RequestRefresh();
}
if (validationFailures == null)
validationFailures = new List<Exception>(1);
validationFailures.Add(ex);
continue;
}
return true;
}
}
return false;
}
}
然后,在您的中间件中,只需访问请求标头、JwtOptions 依赖项并调用 Backer:
protected string ObtainAppTokenFromHeader(string authHeader)
{
if (string.IsNullOrWhiteSpace(authHeader) || !authHeader.Contains(" "))
return null;
string[] authSchemeAndJwt = authHeader.Split(' ');
string authScheme = authSchemeAndJwt[0];
if (authScheme != "Bearer")
return null;
string jwt = authSchemeAndJwt[1];
return jwt;
}
protected async Task<bool> AuthorizeUserFromHttpContext(HttpContext context)
{
var jwtBearerOptions = context.RequestServices.GetRequiredService<JwtBearerOptions>() as JwtBearerOptions;
string jwt = this.ObtainAppTokenFromHeader(context.Request.Headers["Authorization"]);
if (jwt == null)
return false;
var jwtBacker = new JwtBearerBacker(jwtBearerOptions);
return jwtBacker.IsJwtValid(jwt);
}
public async Task Invoke(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
return;
if (!await this.AuthorizeUserFromHttpContext(context))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("The door is locked, dude. You're not authorized !");
return;
}
//... Whatever else you're doing in your middleware
}
此外,AuthenticationTicket 和任何其他有关身份验证的信息已由框架的 JwtBearerMiddleware 处理,并且无论如何都会返回。
最后是客户端。我建议您使用实际上支持附加 HTTP 标头的客户端库。例如,据我所知,W3C Javascript 客户端不提供此功能。
你来了!感谢 Microsoft 的开源代码库。