1 | namespace WebApi.Helpers;
|
---|
2 |
|
---|
3 | using Microsoft.Extensions.Options;
|
---|
4 | using Microsoft.IdentityModel.Tokens;
|
---|
5 | using System.IdentityModel.Tokens.Jwt;
|
---|
6 | using System.Text;
|
---|
7 | using backend.Services;
|
---|
8 | using backend.Helpers;
|
---|
9 |
|
---|
10 | public 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 | } |
---|