JwtTokenMiddleware.cs 781 B

12345678910111213141516171819202122232425
  1. using Microsoft.AspNetCore.Authentication;
  2. using Microsoft.AspNetCore.Authentication.JwtBearer;
  3. using Microsoft.AspNetCore.Builder;
  4. namespace VberAdmin.Authentication.JwtBearer;
  5. public static class JwtTokenMiddleware
  6. {
  7. public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme)
  8. {
  9. return app.Use(async (ctx, next) =>
  10. {
  11. if (ctx.User.Identity?.IsAuthenticated != true)
  12. {
  13. var result = await ctx.AuthenticateAsync(schema);
  14. if (result.Succeeded && result.Principal != null)
  15. {
  16. ctx.User = result.Principal;
  17. }
  18. }
  19. await next();
  20. });
  21. }
  22. }