CookieAuthorizationService.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Principal;
  4. using System.Text;
  5. using System.Linq;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.AspNetCore.Authorization;
  9. using GreenTree.Strohrmann.ERP.Domain.Model;
  10. using System.Security.Claims;
  11. namespace GreenTree.Strohrmann.ERP.Services.Authorization
  12. {
  13. public class CookieAuthorizationService : IAuthorizationService
  14. {
  15. #region Implementation
  16. /// <summary>
  17. /// Check wether the user has a specific policy
  18. /// </summary>
  19. /// <param name="identity">The user identity.</param>
  20. /// <param name="policy">The policy to be checked.</param>
  21. public bool UserHasPolicy(IIdentity identity, string policy)
  22. {
  23. var claimsIdentity = identity as ClaimsIdentity;
  24. if (claimsIdentity == null) return false;
  25. return claimsIdentity.Claims
  26. .Any(c => c.Type == "Policy" && c.Value == policy);
  27. }
  28. /// <summary>
  29. /// Check wether the user has any policy regarding base data management
  30. /// </summary>
  31. /// <param name="identity">The user identity.</param>
  32. public bool UserHasBasedataPolicy(IIdentity identity)
  33. {
  34. var claimsIdentity = identity as ClaimsIdentity;
  35. if (claimsIdentity == null) return false;
  36. return claimsIdentity.Claims
  37. .Any(c => c.Type == "Policy" &&
  38. (c.Value.StartsWith("Customer") ||
  39. c.Value.StartsWith("Employee") ||
  40. c.Value.StartsWith("Material") ||
  41. c.Value.StartsWith("Supplier")));
  42. }
  43. /// <summary>
  44. /// Check wether the user has any policy in a specific category
  45. /// </summary>
  46. /// <param name="identity">The user identity.</param>
  47. /// <param name="category">The category (e.g. 'Customer').</param>
  48. public bool UserHasCategoryPolicy(IIdentity identity, string category)
  49. {
  50. var claimsIdentity = identity as ClaimsIdentity;
  51. if (claimsIdentity == null) return false;
  52. return claimsIdentity.Claims
  53. .Any(c => c.Type == "Policy" && c.Value.StartsWith(category));
  54. }
  55. #endregion
  56. }
  57. }