source: backend/Helpers/JwtMiddleware.cs@ 057037b

Last change on this file since 057037b was 057037b, checked in by Danilo <danilo.najkov@…>, 2 years ago

backend full

  • Property mode set to 100644
File size: 1.7 KB
Line 
1namespace WebApi.Helpers;
2
3using Microsoft.Extensions.Options;
4using Microsoft.IdentityModel.Tokens;
5using System.IdentityModel.Tokens.Jwt;
6using backend.Services;
7using backend.Helpers;
8
9public 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();
35 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
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
48 context.Items["User"] = userId;
49 }
50 catch
51 {
52 // do nothing if jwt validation fails
53 }
54 }
55}
Note: See TracBrowser for help on using the repository browser.