PermissionHandler.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Microsoft.AspNetCore.Authorization;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Fuel.Application.Service;
  9. using Microsoft.AspNetCore.Http;
  10. namespace Fuel.Application.Authorization
  11. {
  12. public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
  13. {
  14. private readonly IUserService _userService;
  15. public PermissionHandler(IUserService userService)
  16. {
  17. _userService = userService;
  18. }
  19. protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
  20. {
  21. bool IsSite = false;//判断是否是子站请求
  22. bool Isbackstage = false;//判断是否是后台请求
  23. string secret_id = string.Empty;
  24. var httpContext = (context.Resource as HttpContext);
  25. if (httpContext != null)
  26. {
  27. if (httpContext.Request.Headers.TryGetValue("secret_id", out var userIdHeader))
  28. {
  29. IsSite = true;
  30. secret_id = userIdHeader.ToString();
  31. }
  32. }
  33. var user = context.User;
  34. int userId = 0;
  35. if (user != null && user.Identity.IsAuthenticated)
  36. {
  37. // 从用户声明中获取用户 ID
  38. var userIdClaim = user.FindFirst(ClaimTypes.NameIdentifier);
  39. if (userIdClaim != null)
  40. {
  41. userId = int.TryParse(userIdClaim.Value, out int number) ? number : 0;
  42. Isbackstage = true;
  43. }
  44. }
  45. if (IsSite || Isbackstage)
  46. {
  47. List<string>? permissions = null;
  48. if (IsSite)
  49. {
  50. // 查询用户权限
  51. permissions = _userService.GetUserPermissions(userId);
  52. }
  53. if (Isbackstage)
  54. {
  55. permissions = _userService.GetSitePermissions(secret_id);
  56. }
  57. // 检查用户是否有权限
  58. if (permissions.Contains(requirement.Permission))
  59. {
  60. context.Succeed(requirement);
  61. }
  62. }
  63. }
  64. }
  65. }