source: backend/Helpers/JwtMiddleware.cs@ b66b3ac

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

Add project files.

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