AuthConfigurer.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Authentication.JwtBearer;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.IdentityModel.Tokens;
  9. using Abp.Runtime.Security;
  10. namespace VberAdmin.Web.Host.Startup;
  11. public static class AuthConfigurer
  12. {
  13. public static void Configure(IServiceCollection services, IConfiguration configuration)
  14. {
  15. if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
  16. {
  17. services.AddAuthentication(options =>
  18. {
  19. options.DefaultAuthenticateScheme = "JwtBearer";
  20. options.DefaultChallengeScheme = "JwtBearer";
  21. }).AddJwtBearer("JwtBearer", options =>
  22. {
  23. options.Audience = configuration["Authentication:JwtBearer:Audience"];
  24. options.TokenValidationParameters = new TokenValidationParameters
  25. {
  26. // The signing key must match!
  27. ValidateIssuerSigningKey = true,
  28. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),
  29. // Validate the JWT Issuer (iss) claim
  30. ValidateIssuer = true,
  31. ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],
  32. // Validate the JWT Audience (aud) claim
  33. ValidateAudience = true,
  34. ValidAudience = configuration["Authentication:JwtBearer:Audience"],
  35. // Validate the token expiry
  36. ValidateLifetime = true,
  37. // If you want to allow a certain amount of clock drift, set that here
  38. ClockSkew = TimeSpan.Zero
  39. };
  40. options.Events = new JwtBearerEvents
  41. {
  42. OnMessageReceived = QueryStringTokenResolver
  43. };
  44. });
  45. }
  46. }
  47. /* This method is needed to authorize SignalR javascript client.
  48. * SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */
  49. private static Task QueryStringTokenResolver(MessageReceivedContext context)
  50. {
  51. if (!context.HttpContext.Request.Path.HasValue ||
  52. !context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
  53. {
  54. // We are just looking for signalr clients
  55. return Task.CompletedTask;
  56. }
  57. var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault();
  58. if (qsAuthToken == null)
  59. {
  60. // Cookie value does not matches to querystring value
  61. return Task.CompletedTask;
  62. }
  63. // Set auth token from cookie
  64. context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken);
  65. return Task.CompletedTask;
  66. }
  67. }