Skip to content

Commit cbaf06e

Browse files
merge pull request #4 from https-richardy/refactor/03-avoid-user-db-lookup-in-principal-middleware
fix(#3): the middleware now directly uses the claims from the authenticated user's context eliminating the need to search for the user in the database
2 parents e685b9b + dc78d6c commit cbaf06e

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

Source/HttpsRichardy.Federation.WebApi/Middlewares/PrincipalMiddleware.cs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,29 @@ public async Task InvokeAsync(HttpContext context)
1717
return;
1818
}
1919

20-
var userCollection = context.RequestServices.GetRequiredService<IUserCollection>();
2120
var userIdClaim = context.User.FindFirst(ClaimTypes.NameIdentifier);
21+
var preferredUsernameClaim = context.User.Claims.FirstOrDefault(claim => claim.Type == "preferred_username");
2222

2323
if (userIdClaim == null || string.IsNullOrWhiteSpace(userIdClaim.Value))
2424
{
2525
await next(context);
2626
return;
2727
}
2828

29-
var filters = UserFilters.WithSpecifications()
30-
.WithIdentifier(userIdClaim.Value)
31-
.Build();
32-
33-
var users = await userCollection.GetUsersAsync(filters, context.RequestAborted);
34-
var user = users.FirstOrDefault();
35-
36-
if (user is not null)
29+
if (preferredUsernameClaim == null || string.IsNullOrWhiteSpace(preferredUsernameClaim.Value))
3730
{
38-
principalProvider.SetPrincipal(user);
31+
await next(context);
32+
return;
3933
}
4034

35+
var principal = new User()
36+
{
37+
Id = userIdClaim.Value,
38+
Username = preferredUsernameClaim.Value
39+
};
40+
41+
principalProvider.SetPrincipal(principal);
42+
4143
await next(context);
4244
}
4345
}

0 commit comments

Comments
 (0)