-
Notifications
You must be signed in to change notification settings - Fork 0
/
JwtClaimsMiddleware.cs
43 lines (37 loc) · 1.52 KB
/
JwtClaimsMiddleware.cs
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
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace PlayOfferService;
public class JwtClaimsMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.ContainsKey("Authorization"))
{
var authorizationHeader = context.Request.Headers["Authorization"].ToString();
if (authorizationHeader.StartsWith("Bearer "))
{
var token = authorizationHeader.Substring("Bearer ".Length).Trim();
try
{
var jwtToken = new JwtSecurityToken(token);
var claims = jwtToken.Claims.ToList();
// Add the Role claims if groups are used as roles
var roleClaims = claims.Where(c => c.Type == "groups")
.Select(c => new Claim(ClaimTypes.Role, c.Value))
.ToList();
// Add role claims to the existing claims list
claims.AddRange(roleClaims);
var claimsIdentity = new ClaimsIdentity(claims, "jwt");
context.User = new ClaimsPrincipal(claimsIdentity);
}
catch (Exception ex)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync("Unauthorized");
return;
}
}
}
await next(context);
}
}