PublicApiCallerExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System.Security.Claims;
  2. namespace Web.Api.Extensions;
  3. /// <summary>
  4. /// 공개 API (/v1/*) 호출 주체 식별.
  5. /// OAuth2 앱 토큰: token_type=oauth2 + app_id claim / PAT: token_type=pat + NameIdentifier(소유 회원).
  6. /// </summary>
  7. public static class PublicApiCallerExtensions
  8. {
  9. public static bool IsOAuth2App(this ClaimsPrincipal user)
  10. {
  11. return user.FindFirst("token_type")?.Value == "oauth2";
  12. }
  13. /// <summary>OAuth2 앱 토큰의 ApplicationID. PAT 등 다른 토큰이면 null.</summary>
  14. public static int? GetApplicationID(this ClaimsPrincipal user)
  15. {
  16. if (!user.IsOAuth2App())
  17. {
  18. return null;
  19. }
  20. return int.TryParse(user.FindFirst("app_id")?.Value, out var id) ? id : null;
  21. }
  22. /// <summary>PAT 토큰의 소유 회원 ID. OAuth2 토큰이면 null.</summary>
  23. public static int? GetPatOwnerMemberID(this ClaimsPrincipal user)
  24. {
  25. if (user.FindFirst("token_type")?.Value != "pat")
  26. {
  27. return null;
  28. }
  29. return int.TryParse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : null;
  30. }
  31. }