-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeycloakAppUserSyncMiddleware.cs
More file actions
61 lines (53 loc) · 2.15 KB
/
KeycloakAppUserSyncMiddleware.cs
File metadata and controls
61 lines (53 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System.Security.Claims;
namespace AzureOpsCrew.Api.Auth;
public sealed class KeycloakAppUserSyncMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<KeycloakAppUserSyncMiddleware> _logger;
public KeycloakAppUserSyncMiddleware(RequestDelegate next, ILogger<KeycloakAppUserSyncMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext, KeycloakAppUserSyncService syncService)
{
var user = httpContext.User;
if (user.Identity?.IsAuthenticated != true)
{
await _next(httpContext);
return;
}
if (user.HasClaim(c => c.Type == AuthenticatedUserExtensions.AppUserIdClaimType))
{
await _next(httpContext);
return;
}
var result = await syncService.EnsureUserAsync(user, httpContext.RequestAborted);
if (!result.IsSuccess)
{
httpContext.Response.StatusCode = result.StatusCode;
await httpContext.Response.WriteAsJsonAsync(
new { error = result.Error ?? "Unauthorized" },
cancellationToken: httpContext.RequestAborted);
return;
}
if (user.Identity is ClaimsIdentity identity)
{
identity.AddClaim(new Claim(AuthenticatedUserExtensions.AppUserIdClaimType, result.UserId.ToString()));
if (!string.IsNullOrWhiteSpace(result.DisplayName) && !user.HasClaim(c => c.Type == AuthenticatedUserExtensions.AppUserDisplayNameClaimType))
{
identity.AddClaim(new Claim(AuthenticatedUserExtensions.AppUserDisplayNameClaimType, result.DisplayName));
}
}
else
{
_logger.LogWarning("Authenticated principal is not a ClaimsIdentity. Rejecting request.");
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
await httpContext.Response.WriteAsJsonAsync(
new { error = "Unauthorized" },
cancellationToken: httpContext.RequestAborted);
return;
}
await _next(httpContext);
}
}