| 1234567891011121314151617181920212223242526272829303132333435 |
- namespace Web.Api.Extensions;
- /// <summary>
- /// 공개 API endpoint scope 검증 필터.
- /// 사용: <c>app.MapGet(...).RequireScope("read:profile")</c>
- /// </summary>
- public static class ScopeAuthorizationExtensions
- {
- public const string ScopeClaimType = "scp";
- public static RouteHandlerBuilder RequireScope(this RouteHandlerBuilder builder, string scope)
- {
- return builder.AddEndpointFilter(async (ctx, next) =>
- {
- var user = ctx.HttpContext.User;
- if (user.Identity?.IsAuthenticated != true)
- {
- return Results.Unauthorized();
- }
- if (!user.HasClaim(ScopeClaimType, scope))
- {
- return Results.Json(new
- {
- type = "https://tools.ietf.org/html/rfc6750#section-3",
- title = "Insufficient Scope",
- status = 403,
- detail = $"Required scope: {scope}"
- }, statusCode: 403, contentType: "application/problem+json");
- }
- return await next(ctx);
- });
- }
- }
|