ResponseAuthenticationHandler.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 
  2. using System;
  3. using System.Text.Encodings.Web;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Authentication;
  7. using Microsoft.Extensions.Logging;
  8. using Microsoft.Extensions.Options;
  9. using Newtonsoft.Json;
  10. using Newtonsoft.Json.Serialization;
  11. using StatusCodes = Admin.Core.Enums.StatusCodes;
  12. using Admin.Core.Common.Extensions;
  13. namespace Admin.Core.Auth
  14. {
  15. /// <summary>
  16. /// 响应认证处理器
  17. /// </summary>
  18. public class ResponseAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
  19. {
  20. public ResponseAuthenticationHandler(
  21. IOptionsMonitor<AuthenticationSchemeOptions> options,
  22. ILoggerFactory logger,
  23. UrlEncoder encoder,
  24. ISystemClock clock
  25. ) : base(options, logger, encoder, clock)
  26. {
  27. }
  28. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  29. {
  30. throw new NotImplementedException();
  31. }
  32. protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
  33. {
  34. Response.ContentType = "application/json";
  35. Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized;
  36. await Response.WriteAsync(JsonConvert.SerializeObject(
  37. new ResponseStatusData
  38. {
  39. Code = StatusCodes.Status401Unauthorized,
  40. Msg = StatusCodes.Status401Unauthorized.ToDescription()
  41. },
  42. new JsonSerializerSettings()
  43. {
  44. ContractResolver = new CamelCasePropertyNamesContractResolver()
  45. }
  46. ));
  47. }
  48. protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
  49. {
  50. Response.ContentType = "application/json";
  51. Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status403Forbidden;
  52. await Response.WriteAsync(JsonConvert.SerializeObject(
  53. new ResponseStatusData
  54. {
  55. Code = StatusCodes.Status403Forbidden,
  56. Msg = StatusCodes.Status403Forbidden.ToDescription()
  57. },
  58. new JsonSerializerSettings()
  59. {
  60. ContractResolver = new CamelCasePropertyNamesContractResolver()
  61. }
  62. ));
  63. }
  64. }
  65. public class ResponseStatusData
  66. {
  67. public StatusCodes Code { get; set; } = StatusCodes.Status1Ok;
  68. public string Msg { get; set; }
  69. }
  70. }