ResponseAuthenticationHandler.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. namespace Admin.Core.Auth
  13. {
  14. /// <summary>
  15. /// 响应认证处理器
  16. /// </summary>
  17. public class ResponseAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
  18. {
  19. public ResponseAuthenticationHandler(
  20. IOptionsMonitor<AuthenticationSchemeOptions> options,
  21. ILoggerFactory logger,
  22. UrlEncoder encoder,
  23. ISystemClock clock
  24. ) : base(options, logger, encoder, clock)
  25. {
  26. }
  27. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  28. {
  29. throw new NotImplementedException();
  30. }
  31. protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
  32. {
  33. Response.ContentType = "application/json";
  34. Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized;
  35. await Response.WriteAsync(JsonConvert.SerializeObject(
  36. new ResponseStatusData
  37. {
  38. Code = StatusCodes.Status401Unauthorized,
  39. Msg = StatusCodes.Status401Unauthorized.ToDescriptionOrString()
  40. },
  41. new JsonSerializerSettings()
  42. {
  43. ContractResolver = new CamelCasePropertyNamesContractResolver()
  44. }
  45. ));
  46. }
  47. protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
  48. {
  49. Response.ContentType = "application/json";
  50. Response.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status403Forbidden;
  51. await Response.WriteAsync(JsonConvert.SerializeObject(
  52. new ResponseStatusData
  53. {
  54. Code = StatusCodes.Status403Forbidden,
  55. Msg = StatusCodes.Status403Forbidden.ToDescriptionOrString()
  56. },
  57. new JsonSerializerSettings()
  58. {
  59. ContractResolver = new CamelCasePropertyNamesContractResolver()
  60. }
  61. ));
  62. }
  63. }
  64. public class ResponseStatusData
  65. {
  66. public StatusCodes Code { get; set; } = StatusCodes.Status1Ok;
  67. public string Msg { get; set; }
  68. }
  69. }