Hope this can help someone, although the post is old.
I found out the answer, not after Googling, but Binging! I inspired myself with this official code .
You can write your own class that handles authorization very simply using the magic of JwtBearerOptions. This class (hopefully) contains everything you need to test the JWT yourself.
So, you must enter it as a Service, and use it to configure authentication. Something like this in your Startup.ConfigureServices :
this.JwtOptions = new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = yourTokenValidationParameters }; services.AddSingleton<JwtBearerOptions>(this.JwtOptions);
Then you need to create a class that will validate your token ( Here my code was inspired ). Let me call him Protector because he brought you back !:
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) {
Then in your middleware, just go into the request header, the JwtOptions dependency and call 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; }
In addition, AuthenticationTicket and any other auth information is already being processed by the JwtBearerMiddleware and will be returned anyway.
Finally, the client side. I advise you to use a client library that actually supports additional HTTP headers. For example, as far as I know, the W3C Javascript client does not provide this functionality.
Here you! Thanks to Microsoft for its open source codebase.