ClaimsIdentityExtensions.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Linq;
  3. using System.Security.Claims;
  4. using System.Security.Principal;
  5. using Abp.Extensions;
  6. using JetBrains.Annotations;
  7. namespace Abp.Runtime.Security
  8. {
  9. public static class ClaimsIdentityExtensions
  10. {
  11. public static UserIdentifier GetUserIdentifierOrNull(this IIdentity identity)
  12. {
  13. Check.NotNull(identity, nameof(identity));
  14. var userId = identity.GetUserId();
  15. if (userId == null)
  16. {
  17. return null;
  18. }
  19. return new UserIdentifier(identity.GetTenantId(), userId.Value);
  20. }
  21. public static long? GetUserId([NotNull] this IIdentity identity)
  22. {
  23. Check.NotNull(identity, nameof(identity));
  24. var claimsIdentity = identity as ClaimsIdentity;
  25. var userIdOrNull = claimsIdentity?.Claims?.FirstOrDefault(c => c.Type == AbpClaimTypes.UserId);
  26. if (userIdOrNull == null || userIdOrNull.Value.IsNullOrWhiteSpace())
  27. {
  28. return null;
  29. }
  30. return Convert.ToInt64(userIdOrNull.Value);
  31. }
  32. public static int? GetTenantId(this IIdentity identity)
  33. {
  34. Check.NotNull(identity, nameof(identity));
  35. var claimsIdentity = identity as ClaimsIdentity;
  36. var tenantIdOrNull = claimsIdentity?.Claims?.FirstOrDefault(c => c.Type == AbpClaimTypes.TenantId);
  37. if (tenantIdOrNull == null || tenantIdOrNull.Value.IsNullOrWhiteSpace())
  38. {
  39. return null;
  40. }
  41. return Convert.ToInt32(tenantIdOrNull.Value);
  42. }
  43. public static long? GetImpersonatorUserId(this IIdentity identity)
  44. {
  45. Check.NotNull(identity, nameof(identity));
  46. var claimsIdentity = identity as ClaimsIdentity;
  47. var userIdOrNull = claimsIdentity?.Claims?.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorUserId);
  48. if (userIdOrNull == null || userIdOrNull.Value.IsNullOrWhiteSpace())
  49. {
  50. return null;
  51. }
  52. return Convert.ToInt64(userIdOrNull.Value);
  53. }
  54. public static int? GetImpersonatorTenantId(this IIdentity identity)
  55. {
  56. Check.NotNull(identity, nameof(identity));
  57. var claimsIdentity = identity as ClaimsIdentity;
  58. var tenantIdOrNull = claimsIdentity?.Claims?.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorTenantId);
  59. if (tenantIdOrNull == null || tenantIdOrNull.Value.IsNullOrWhiteSpace())
  60. {
  61. return null;
  62. }
  63. return Convert.ToInt32(tenantIdOrNull.Value);
  64. }
  65. }
  66. }