-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathServerAuthHelper.cs
213 lines (187 loc) · 8.73 KB
/
ServerAuthHelper.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Stl.Fusion.Authentication;
using Stl.Fusion.Server.Internal;
using Stl.Multitenancy;
namespace Stl.Fusion.Server.Authentication;
public class ServerAuthHelper : IHasServices
{
public record Options
{
public static Options Default { get; set; } = new();
public string[] IdClaimKeys { get; init; } = { ClaimTypes.NameIdentifier };
public string[] NameClaimKeys { get; init; } = { ClaimTypes.Name };
public string CloseWindowRequestPath { get; init; } = "/fusion/close";
public TimeSpan SessionInfoUpdatePeriod { get; init; } = TimeSpan.FromSeconds(30);
public bool KeepSignedIn { get; init; }
}
protected IAuth Auth { get; }
protected IAuthBackend AuthBackend { get; }
protected ISessionResolver SessionResolver { get; }
protected AuthSchemasCache AuthSchemasCache { get; }
protected ITenantResolver TenantResolver { get; }
protected ICommander Commander { get; }
protected MomentClockSet Clocks { get; }
public Options Settings { get; }
public IServiceProvider Services { get; }
public ILogger Log { get; }
public Session Session => SessionResolver.Session;
public ServerAuthHelper(Options settings, IServiceProvider services)
{
Settings = settings;
Services = services;
Log = services.LogFor(GetType());
Auth = services.GetRequiredService<IAuth>();
AuthBackend = services.GetRequiredService<IAuthBackend>();
SessionResolver = services.GetRequiredService<ISessionResolver>();
AuthSchemasCache = services.GetRequiredService<AuthSchemasCache>();
TenantResolver = services.GetRequiredService<ITenantResolver>();
Commander = services.Commander();
Clocks = services.Clocks();
}
public virtual async ValueTask<string> GetSchemas(HttpContext httpContext, bool cache = true)
{
string? schemas;
if (cache) {
schemas = AuthSchemasCache.Schemas;
if (schemas != null)
return schemas;
}
var authSchemas = await httpContext.GetAuthenticationSchemas().ConfigureAwait(false);
var lSchemas = new List<string>();
foreach (var authSchema in authSchemas) {
lSchemas.Add(authSchema.Name);
lSchemas.Add(authSchema.DisplayName ?? authSchema.Name);
}
schemas = ListFormat.Default.Format(lSchemas);
if (cache)
AuthSchemasCache.Schemas = schemas;
return schemas;
}
public Task UpdateAuthState(HttpContext httpContext, CancellationToken cancellationToken = default)
=> UpdateAuthState(SessionResolver.Session, httpContext, cancellationToken);
public virtual async Task UpdateAuthState(
Session session,
HttpContext httpContext,
CancellationToken cancellationToken = default)
{
var httpUser = httpContext.User;
var httpAuthenticationSchema = httpUser.Identity?.AuthenticationType ?? "";
var httpIsAuthenticated = !httpAuthenticationSchema.IsNullOrEmpty();
var ipAddress = httpContext.GetRemoteIPAddress()?.ToString() ?? "";
var userAgent = httpContext.Request.Headers.TryGetValue("User-Agent", out var userAgentValues)
? userAgentValues.FirstOrDefault() ?? ""
: "";
var sessionInfo = await GetSessionInfo(session, cancellationToken).ConfigureAwait(false);
var mustSetupSession =
sessionInfo == null
|| !StringComparer.Ordinal.Equals(sessionInfo.IPAddress, ipAddress)
|| !StringComparer.Ordinal.Equals(sessionInfo.UserAgent, userAgent)
|| sessionInfo.LastSeenAt + Settings.SessionInfoUpdatePeriod < Clocks.SystemClock.Now;
if (mustSetupSession || sessionInfo == null)
sessionInfo = await SetupSession(session, sessionInfo, ipAddress, userAgent, cancellationToken)
.ConfigureAwait(false);
var user = await GetUser(session, sessionInfo, cancellationToken).ConfigureAwait(false);
try {
if (httpIsAuthenticated) {
if (IsSameUser(user, httpUser, httpAuthenticationSchema))
return;
await SignIn(session, sessionInfo, user, httpUser, httpAuthenticationSchema, cancellationToken)
.ConfigureAwait(false);
}
else if (user != null && !Settings.KeepSignedIn) {
await SignOut(session, sessionInfo, cancellationToken).ConfigureAwait(false);
}
}
finally {
// This should be done once important things are completed
await UpdatePresence(session, sessionInfo, cancellationToken).ConfigureAwait(false);
}
}
public virtual bool IsCloseWindowRequest(HttpContext httpContext, out string closeWindowFlowName)
{
var request = httpContext.Request;
var isCloseWindowRequest = StringComparer.Ordinal.Equals(request.Path.Value, Settings.CloseWindowRequestPath);
closeWindowFlowName = "";
if (isCloseWindowRequest && request.Query.TryGetValue("flow", out var flows))
closeWindowFlowName = flows.FirstOrDefault() ?? "";
return isCloseWindowRequest;
}
// Protected methods
protected virtual Task<SessionInfo?> GetSessionInfo(Session session, CancellationToken cancellationToken)
=> Auth.GetSessionInfo(session, cancellationToken);
protected virtual Task<User?> GetUser(
Session session, SessionInfo sessionInfo,
CancellationToken cancellationToken)
=> Auth.GetUser(session, cancellationToken);
protected virtual Task<SessionInfo> SetupSession(
Session session, SessionInfo? sessionInfo, string ipAddress, string userAgent,
CancellationToken cancellationToken)
{
var setupSessionCommand = new AuthBackend_SetupSession(session, ipAddress, userAgent);
return Commander.Call(setupSessionCommand, true, cancellationToken);
}
protected virtual Task SignIn(
Session session, SessionInfo sessionInfo,
User? user, ClaimsPrincipal httpUser, string httpAuthenticationSchema,
CancellationToken cancellationToken)
{
var (newUser, authenticatedIdentity) = CreateOrUpdateUser(user, httpUser, httpAuthenticationSchema);
var signInCommand = new AuthBackend_SignIn(session, newUser, authenticatedIdentity);
return Commander.Call(signInCommand, true, cancellationToken);
}
protected virtual Task SignOut(
Session session, SessionInfo sessionInfo,
CancellationToken cancellationToken)
{
var signOutCommand = new Auth_SignOut(session);
return Commander.Call(signOutCommand, true, cancellationToken);
}
protected virtual Task UpdatePresence(
Session session, SessionInfo sessionInfo,
CancellationToken cancellationToken)
{
_ = Auth.UpdatePresence(session, CancellationToken.None);
return Task.CompletedTask;
}
protected virtual bool IsSameUser(User? user, ClaimsPrincipal httpUser, string schema)
{
if (user == null) return false;
var httpUserIdentityName = httpUser.Identity?.Name ?? "";
var claims = httpUser.Claims.ToImmutableDictionary(c => c.Type, c => c.Value);
var id = FirstClaimOrDefault(claims, Settings.IdClaimKeys) ?? httpUserIdentityName;
var identity = new UserIdentity(schema, id);
return user.Identities.ContainsKey(identity);
}
protected virtual (User User, UserIdentity AuthenticatedIdentity) CreateOrUpdateUser(
User? user, ClaimsPrincipal httpUser, string schema)
{
var httpUserIdentityName = httpUser.Identity?.Name ?? "";
var claims = httpUser.Claims.ToImmutableDictionary(c => c.Type, c => c.Value);
var id = FirstClaimOrDefault(claims, Settings.IdClaimKeys) ?? httpUserIdentityName;
var name = FirstClaimOrDefault(claims, Settings.NameClaimKeys) ?? httpUserIdentityName;
var identity = new UserIdentity(schema, id);
var identities = ImmutableDictionary<UserIdentity, string>.Empty.Add(identity, "");
if (user == null)
// Create
user = new User(Symbol.Empty, name) {
Claims = claims,
Identities = identities,
};
else {
// Update
user = user with {
Claims = claims.SetItems(user.Claims),
Identities = identities,
};
}
return (user, identity);
}
protected static string? FirstClaimOrDefault(IReadOnlyDictionary<string, string> claims, string[] keys)
{
foreach (var key in keys)
if (claims.TryGetValue(key, out var value) && !value.IsNullOrEmpty())
return value;
return null;
}
}