[b66b3ac] | 1 | namespace WebApi.Helpers;
|
---|
| 2 |
|
---|
| 3 | using Microsoft.Extensions.Options;
|
---|
| 4 | using Microsoft.IdentityModel.Tokens;
|
---|
| 5 | using System.IdentityModel.Tokens.Jwt;
|
---|
| 6 | using backend.Services;
|
---|
| 7 | using backend.Helpers;
|
---|
| 8 |
|
---|
| 9 | public class JwtMiddleware
|
---|
| 10 | {
|
---|
| 11 | private readonly RequestDelegate _next;
|
---|
| 12 | private readonly AppSettings _appSettings;
|
---|
| 13 |
|
---|
| 14 | public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings)
|
---|
| 15 | {
|
---|
| 16 | _next = next;
|
---|
| 17 | _appSettings = appSettings.Value;
|
---|
| 18 | }
|
---|
| 19 |
|
---|
| 20 | public async Task Invoke(HttpContext context, IUserService userService)
|
---|
| 21 | {
|
---|
| 22 | var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
---|
| 23 |
|
---|
| 24 | if (token != null)
|
---|
| 25 | attachUserToContext(context, userService, token);
|
---|
| 26 |
|
---|
| 27 | await _next(context);
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | private void attachUserToContext(HttpContext context, IUserService userService, string token)
|
---|
| 31 | {
|
---|
| 32 | try
|
---|
| 33 | {
|
---|
| 34 | var tokenHandler = new JwtSecurityTokenHandler();
|
---|
[057037b] | 35 | var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
|
---|
[b66b3ac] | 36 | tokenHandler.ValidateToken(token, new TokenValidationParameters
|
---|
| 37 | {
|
---|
| 38 | ValidateIssuerSigningKey = true,
|
---|
| 39 | IssuerSigningKey = new SymmetricSecurityKey(key),
|
---|
| 40 | ValidateIssuer = false,
|
---|
| 41 | ValidateAudience = false,
|
---|
| 42 | ClockSkew = TimeSpan.Zero
|
---|
| 43 | }, out SecurityToken validatedToken);
|
---|
| 44 |
|
---|
| 45 | var jwtToken = (JwtSecurityToken)validatedToken;
|
---|
| 46 | var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
|
---|
| 47 |
|
---|
[057037b] | 48 | context.Items["User"] = userId;
|
---|
[b66b3ac] | 49 | }
|
---|
| 50 | catch
|
---|
| 51 | {
|
---|
| 52 | // do nothing if jwt validation fails
|
---|
| 53 | }
|
---|
| 54 | }
|
---|
| 55 | } |
---|