ScopeAuthorizationExtensions.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. namespace Web.Api.Extensions;
  2. /// <summary>
  3. /// 공개 API endpoint scope 검증 필터.
  4. /// 사용: <c>app.MapGet(...).RequireScope("read:profile")</c>
  5. /// </summary>
  6. public static class ScopeAuthorizationExtensions
  7. {
  8. public const string ScopeClaimType = "scp";
  9. public static RouteHandlerBuilder RequireScope(this RouteHandlerBuilder builder, string scope)
  10. {
  11. return builder.AddEndpointFilter(async (ctx, next) =>
  12. {
  13. var user = ctx.HttpContext.User;
  14. if (user.Identity?.IsAuthenticated != true)
  15. {
  16. return Results.Unauthorized();
  17. }
  18. if (!user.HasClaim(ScopeClaimType, scope))
  19. {
  20. return Results.Json(new
  21. {
  22. type = "https://tools.ietf.org/html/rfc6750#section-3",
  23. title = "Insufficient Scope",
  24. status = 403,
  25. detail = $"Required scope: {scope}"
  26. }, statusCode: 403, contentType: "application/problem+json");
  27. }
  28. return await next(ctx);
  29. });
  30. }
  31. }