-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrincipalMiddleware.cs
More file actions
54 lines (42 loc) · 1.7 KB
/
Copy pathPrincipalMiddleware.cs
File metadata and controls
54 lines (42 loc) · 1.7 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
namespace Comanda.Orchestrator.WebApi.Middlewares;
public sealed class PrincipalMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
var principalProvider = context.RequestServices.GetRequiredService<IPrincipalProvider>();
principalProvider.Clear();
var endpoint = context.GetEndpoint();
var requiresAuth = endpoint?.Metadata.GetMetadata<AuthorizeAttribute>() != null;
if (!requiresAuth || context.User.Identity?.IsAuthenticated != true)
{
await next(context);
return;
}
var userName = context.User.Claims.FirstOrDefault(claim => claim.Type == "preferred_username");
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier);
if (userId == null || string.IsNullOrWhiteSpace(userId.Value))
{
await next(context);
return;
}
if (userName == null || string.IsNullOrWhiteSpace(userName.Value))
{
await next(context);
return;
}
principalProvider.SetPrincipal(new User(userId.Value, userName.Value));
/* enriches logging and monitoring contexts with user information */
/* enabling traceability of user actions across logs and error monitoring tools */
using (LogContext.PushProperty("user_id", userId.Value))
using (LogContext.PushProperty("user_name", userName.Value))
using (SentrySdk.PushScope())
{
SentrySdk.ConfigureScope(scope =>
{
scope.SetTag("user_id", userId.Value);
scope.SetTag("user_name", userName.Value);
});
await next(context);
}
}
}