-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Aug-8 <130132558+sol-wizard@users.noreply.github.com>
- Loading branch information
1 parent
5f307cd
commit 754c0f9
Showing
4 changed files
with
48 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using System.Security.Claims; | ||
|
||
public class UserContextMiddleware | ||
{ | ||
private readonly RequestDelegate _next; | ||
private readonly ILogger<UserContextMiddleware> _logger; | ||
|
||
public UserContextMiddleware(RequestDelegate next, ILogger<UserContextMiddleware> logger) | ||
{ | ||
_next = next; | ||
_logger = logger; | ||
} | ||
|
||
public async Task InvokeAsync(HttpContext context) | ||
{ | ||
// Check if the user is authenticated | ||
if (context.User.Identity?.IsAuthenticated == true) | ||
{ | ||
// Extract UserId from the claims | ||
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; | ||
|
||
if (userId == null) | ||
{ | ||
_logger.LogError("Unable to get user Id in UserContextMiddleware for an authenticated user."); | ||
throw new UnauthorizedAccessException("Unable to get user Id in UserContextMiddleware."); | ||
} | ||
|
||
// Store UserId in HttpContext.Items | ||
context.Items["UserId"] = userId; | ||
} | ||
|
||
// Pass request to the next middleware in the pipeline | ||
await _next(context); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters