-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathOrleansIdentityAuthenticationHandler.cs
More file actions
73 lines (65 loc) · 2.45 KB
/
OrleansIdentityAuthenticationHandler.cs
File metadata and controls
73 lines (65 loc) · 2.45 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
using System;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using ManagedCode.Orleans.Identity.Core.Constants;
using ManagedCode.Orleans.Identity.Core.Extensions;
using ManagedCode.Orleans.Identity.Core.Interfaces;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
namespace ManagedCode.Orleans.Identity.Client.Middlewares;
public class OrleansIdentityAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IClusterClient client) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder, clock)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string sessionId;
if (!Request.Headers.TryGetValue(OrleansIdentityConstants.AUTH_TOKEN, out var values))
{
if (Request.Headers.TryGetValue("Authorization", out var jwt))
{
sessionId = jwt.ToString().Replace("Bearer", "").Trim();
}
else if (Request.Query.TryGetValue(OrleansIdentityConstants.AUTH_TOKEN, out var queryValues))
{
sessionId = queryValues.ToString().Trim();
}
else
{
return AuthenticateResult.NoResult();
}
}
else
{
sessionId = values.ToString().Trim();
}
if (string.IsNullOrEmpty(sessionId))
{
return AuthenticateResult.NoResult();
}
try
{
var sessionGrain = client.GetGrain<ISessionGrain>(sessionId);
var result = await sessionGrain.ValidateAndGetClaimsAsync();
if (result.IsSuccess)
{
ClaimsIdentity claimsIdentity = new(OrleansIdentityConstants.AUTHENTICATION_TYPE);
foreach (var claim in result.Value!)
claimsIdentity.ParseClaims(claim.Key, claim.Value);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
catch (Exception e)
{
Logger.LogError(e, "HandleAuthenticateAsync Validation");
}
return AuthenticateResult.Fail($"Unauthorized request. SessionId: {sessionId};");
}
}