-
Notifications
You must be signed in to change notification settings - Fork 0
/
CurrentUserFilter.cs
47 lines (39 loc) · 1.48 KB
/
CurrentUserFilter.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
44
45
46
47
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using JsonApiDotNetCore.Internal;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace LibraryApi
{
public class CurrentUserFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var httpContext = context.HttpContext;
var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault(a => a.Contains("Bearer "));
if (authHeader == null)
{
throw new JsonApiException(401, "Unauthorized");
}
var token = authHeader.Replace("Bearer ", "");
var securityKey = httpContext.RequestServices.GetRequiredService<SymmetricSecurityKey>();
try
{
var userClaim = new JwtSecurityTokenHandler().ValidateToken(token, new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = securityKey
}, out var ValidatedToken);
httpContext.User = userClaim;
}
catch (SecurityTokenException)
{
throw new JsonApiException(401, "Unauthorized");
}
}
}
}