Skip to content

Commit 76e44d0

Browse files
Use custom handler
1 parent 1c1cf81 commit 76e44d0

File tree

2 files changed

+50
-5
lines changed

2 files changed

+50
-5
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using Microsoft.AspNetCore.Authorization.Policy;
2+
using Microsoft.AspNetCore.Authorization;
3+
4+
namespace mnestix_proxy.Authentication.ApiKeyAuthentication
5+
{
6+
public class CustomAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
7+
{
8+
private readonly AuthorizationMiddlewareResultHandler _defaultHandler = new();
9+
10+
public async Task HandleAsync(RequestDelegate next, HttpContext context,
11+
AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
12+
{
13+
if (authorizeResult.Forbidden)
14+
{
15+
context.Response.StatusCode = StatusCodes.Status403Forbidden;
16+
context.Response.ContentType = "application/json";
17+
18+
var message = "Forbidden";
19+
if (authorizeResult.AuthorizationFailure?.FailureReasons?.Any() == true)
20+
{
21+
message = authorizeResult.AuthorizationFailure.FailureReasons
22+
.Select(r => r.Message)
23+
.FirstOrDefault() ?? message;
24+
}
25+
26+
await context.Response.WriteAsJsonAsync(new { error = message });
27+
return;
28+
}
29+
30+
if (authorizeResult.Challenged)
31+
{
32+
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
33+
context.Response.ContentType = "application/json";
34+
35+
await context.Response.WriteAsJsonAsync(new
36+
{
37+
error = "Unauthorized: You must provide valid authentication credentials."
38+
});
39+
return;
40+
}
41+
42+
// Proceed normally
43+
await _defaultHandler.HandleAsync(next, context, policy, authorizeResult);
44+
}
45+
}
46+
47+
}

mnestix-proxy/Authentication/AuthenticationServicesRegistration.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using Microsoft.AspNetCore.Authentication.JwtBearer;
2+
using Microsoft.AspNetCore.Authorization;
23
using Microsoft.Identity.Web;
34
using Microsoft.IdentityModel.Tokens;
5+
using mnestix_proxy.Authentication.ApiKeyAuthentication;
46

57
namespace mnestix_proxy.Authentication;
68

@@ -55,11 +57,7 @@ public static void AddAuthenticationServices(this IServiceCollection services, I
5557
services.AddMicrosoftIdentityWebApiAuthentication(configuration);
5658
}
5759
else {
58-
services.AddAuthentication(options =>
59-
{
60-
options.DefaultAuthenticateScheme = null;
61-
options.DefaultChallengeScheme = null;
62-
});
60+
services.AddSingleton<IAuthorizationMiddlewareResultHandler, CustomAuthorizationMiddlewareResultHandler>();
6361
}
6462
}
6563
}

0 commit comments

Comments
 (0)