-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathApiTokenAuthentication.cs
More file actions
96 lines (81 loc) · 3.66 KB
/
ApiTokenAuthentication.cs
File metadata and controls
96 lines (81 loc) · 3.66 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System.Net.Mime;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OpenShock.Common.Authentication.Services;
using OpenShock.Common.Errors;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.BatchUpdate;
using OpenShock.Common.Utils;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using OpenShock.Common.Problems;
namespace OpenShock.Common.Authentication.AuthenticationHandlers;
public sealed class ApiTokenAuthentication : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IClientAuthService<User> _authService;
private readonly IUserReferenceService _userReferenceService;
private readonly IBatchUpdateService _batchUpdateService;
private readonly OpenShockContext _db;
private readonly JsonSerializerOptions _serializerOptions;
private OpenShockProblem? _authResultError = null;
public ApiTokenAuthentication(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
IClientAuthService<User> clientAuth,
IUserReferenceService userReferenceService,
OpenShockContext db,
IOptions<JsonOptions> jsonOptions, IBatchUpdateService batchUpdateService)
: base(options, logger, encoder)
{
_authService = clientAuth;
_userReferenceService = userReferenceService;
_db = db;
_serializerOptions = jsonOptions.Value.SerializerOptions;
_batchUpdateService = batchUpdateService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Context.TryGetApiTokenFromHeader(out var token))
{
return Fail(AuthResultError.HeaderMissingOrInvalid);
}
var tokenHash = HashingUtils.HashToken(token);
var tokenDto = await _db.ApiTokens.Include(x => x.User).FirstOrDefaultAsync(x => x.TokenHash == tokenHash &&
(x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow));
if (tokenDto == null) return Fail(AuthResultError.TokenInvalid);
_batchUpdateService.UpdateApiTokenLastUsed(tokenDto.Id);
_authService.CurrentClient = tokenDto.User;
_userReferenceService.AuthReference = tokenDto;
List<Claim> claims = [
new(ClaimTypes.AuthenticationMethod, OpenShockAuthSchemas.ApiToken),
new(ClaimTypes.NameIdentifier, tokenDto.User.Id.ToString()),
new(OpenShockAuthClaims.ApiTokenId, tokenDto.Id.ToString())
];
foreach (var perm in tokenDto.Permissions)
{
claims.Add(new(OpenShockAuthClaims.ApiTokenPermission, perm.ToString()));
}
var ident = new ClaimsIdentity(claims, nameof(ApiTokenAuthentication));
Context.User = new ClaimsPrincipal(ident);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(ident), Scheme.Name);
return AuthenticateResult.Success(ticket);
}
private AuthenticateResult Fail(OpenShockProblem reason)
{
_authResultError = reason;
return AuthenticateResult.Fail(reason.Type!);
}
/// <inheritdoc />
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (Context.Response.HasStarted) return Task.CompletedTask;
_authResultError ??= AuthResultError.UnknownError;
Response.StatusCode = _authResultError.Status!.Value;
_authResultError.AddContext(Context);
return Context.Response.WriteAsJsonAsync(_authResultError, _serializerOptions, contentType: MediaTypeNames.Application.ProblemJson);
}
}