/
AuthProviderSync.cs
453 lines (379 loc) · 18.5 KB
/
AuthProviderSync.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Configuration;
using ServiceStack.Host;
using ServiceStack.Logging;
using ServiceStack.Web;
namespace ServiceStack.Auth
{
/// <summary>
/// Sync AuthProvider base class for compatibility with Sync Auth Providers
/// </summary>
public abstract class AuthProviderSync : IAuthProvider, IAuthPlugin
{
protected static readonly ILog Log = LogManager.GetLogger(typeof(AuthProviderSync));
public virtual string Type => GetType().Name;
public virtual Dictionary<string, string> Meta => null;
public TimeSpan? SessionExpiry { get; set; }
public string AuthRealm { get; set; }
public string Provider { get; set; }
public string CallbackUrl { get; set; }
public string RedirectUrl { get; set; }
public bool PersistSession { get; set; }
public bool SaveExtendedUserInfo { get; set; }
public bool? RestoreSessionFromState { get; set; }
public Action<AuthUserSession, IAuthTokens, Dictionary<string, string>> LoadUserAuthFilter { get; set; }
public Func<AuthContext, IHttpResult> CustomValidationFilter { get; set; }
public Func<AuthProviderSync, string, string> PreAuthUrlFilter = UrlFilter;
public Func<AuthProviderSync, string, string> AccessTokenUrlFilter = UrlFilter;
public Func<AuthProviderSync, string, string> SuccessRedirectUrlFilter = UrlFilter;
public Func<AuthProviderSync, string, string> FailedRedirectUrlFilter = UrlFilter;
public Func<AuthProviderSync, string, string> LogoutUrlFilter = UrlFilter;
public Func<IAuthRepository, IUserAuth, IAuthTokens, bool> AccountLockedValidator { get; set; }
public static string UrlFilter(AuthProviderSync provider, string url) => url;
public NavItem NavItem { get; set; }
protected AuthProviderSync()
{
PersistSession = !GetType().HasInterface(typeof(IAuthWithRequest));
}
protected AuthProviderSync(IAppSettings appSettings, string authRealm, string oAuthProvider)
: this()
{
// Enhancement per https://github.com/ServiceStack/ServiceStack/issues/741
this.AuthRealm = appSettings != null ? appSettings.Get("OAuthRealm", authRealm) : authRealm;
this.Provider = oAuthProvider;
if (appSettings != null)
{
this.CallbackUrl = appSettings.GetString($"oauth.{oAuthProvider}.CallbackUrl")
?? FallbackConfig(appSettings.GetString("oauth.CallbackUrl"));
this.RedirectUrl = appSettings.GetString($"oauth.{oAuthProvider}.RedirectUrl")
?? FallbackConfig(appSettings.GetString("oauth.RedirectUrl"));
}
}
public IAuthEvents AuthEvents => HostContext.TryResolve<IAuthEvents>() ?? new AuthEvents();
/// <summary>
/// Allows specifying a global fallback config that if exists is formatted with the Provider as the first arg.
/// E.g. this appSetting with the TwitterAuthProvider:
/// oauth.CallbackUrl="http://localhost:11001/auth/{0}"
/// Would result in:
/// oauth.CallbackUrl="http://localhost:11001/auth/twitter"
/// </summary>
/// <returns></returns>
protected string FallbackConfig(string fallback)
{
return fallback?.Fmt(Provider);
}
/// <summary>
/// Remove the Users Session
/// </summary>
/// <param name="service"></param>
/// <param name="request"></param>
/// <returns></returns>
public virtual object Logout(IServiceBase service, Authenticate request)
{
var feature = HostContext.GetPlugin<AuthFeature>();
var session = service.GetSession();
var referrerUrl = service.Request.GetReturnUrl()
?? (feature.HtmlLogoutRedirect != null ? service.Request.ResolveAbsoluteUrl(feature.HtmlLogoutRedirect) : null)
?? session.ReferrerUrl
?? service.Request.GetHeader("Referer").NotLogoutUrl()
?? this.RedirectUrl;
session.OnLogout(service);
AuthEvents.OnLogout(service.Request, session, service);
service.RemoveSession();
if (feature != null && feature.DeleteSessionCookiesOnLogout)
{
service.Request.Response.DeleteSessionCookies();
service.Request.Response.DeleteJwtCookie();
}
if (service.Request.ResponseContentType == MimeTypes.Html && !string.IsNullOrEmpty(referrerUrl))
return service.Redirect(LogoutUrlFilter(this, referrerUrl));
return new AuthenticateResponse();
}
public HashSet<string> ExcludeAuthInfoItems { get; set; } = new HashSet<string>(new[]{ "user_id", "email", "username", "name", "first_name", "last_name", "email" }, StringComparer.OrdinalIgnoreCase);
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
session.AuthProvider = Provider;
if (session is AuthUserSession userSession)
{
LoadUserAuthInfo(userSession, tokens, authInfo);
HostContext.TryResolve<IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
LoadUserAuthFilter?.Invoke(userSession, tokens, authInfo);
}
var hasTokens = tokens != null && authInfo != null;
if (hasTokens && SaveExtendedUserInfo)
{
if (tokens.Items == null)
tokens.Items = new Dictionary<string, string>();
foreach (var entry in authInfo)
{
if (ExcludeAuthInfoItems.Contains(entry.Key))
continue;
tokens.Items[entry.Key] = entry.Value;
}
}
if (session is IAuthSessionExtended authSession)
{
var failed = authSession.Validate(authService, session, tokens, authInfo)
?? AuthEvents.Validate(authService, session, tokens, authInfo);
if (failed != null)
{
authService.RemoveSession();
return failed;
}
}
var authRepo = GetAuthRepository(authService.Request);
using (authRepo as IDisposable)
{
if (CustomValidationFilter != null)
{
var ctx = new AuthContext
{
Request = authService.Request,
Service = authService,
AuthProviderSync = this,
Session = session,
AuthTokens = tokens,
AuthInfo = authInfo,
AuthRepository = authRepo,
};
var response = CustomValidationFilter(ctx);
if (response != null)
{
authService.RemoveSession();
return response;
}
}
if (authRepo != null)
{
var failed = ValidateAccount(authService, authRepo, session, tokens);
if (failed != null)
{
authService.RemoveSession();
return failed;
}
if (hasTokens)
{
var authDetails = authRepo.CreateOrMergeAuthSession(session, tokens);
session.UserAuthId = authDetails.UserAuthId.ToString();
var firstTimeAuthenticated = authDetails.CreatedDate == authDetails.ModifiedDate;
if (firstTimeAuthenticated)
{
session.OnRegistered(authService.Request, session, authService);
AuthEvents.OnRegistered(authService.Request, session, authService);
}
}
authRepo.LoadUserAuth(session, tokens);
foreach (var oAuthToken in session.GetAuthTokens())
{
var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
var userAuthProvider = authProvider as OAuthProvider;
userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
}
var httpRes = authService.Request.Response as IHttpResponse;
if (session.UserAuthId != null)
{
httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
}
}
else
{
if (hasTokens)
{
session.UserAuthId = CreateOrMergeAuthSession(session, tokens);
}
}
}
try
{
session.IsAuthenticated = true;
session.OnAuthenticated(authService, session, tokens, authInfo);
AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
}
finally
{
#pragma warning disable 618
this.SaveSession(authService, session, SessionExpiry);
#pragma warning restore 618
authService.Request.Items[Keywords.DidAuthenticate] = true;
}
return null;
}
protected virtual IAuthRepository GetAuthRepository(IRequest req)
{
return HostContext.AppHost.GetAuthRepository(req);
}
// Keep in-memory map of userAuthId's when no IAuthRepository exists
private static long transientUserAuthId;
static readonly ConcurrentDictionary<string, long> transientUserIdsMap = new ConcurrentDictionary<string, long>();
// Merge tokens into session when no IAuthRepository exists
public virtual string CreateOrMergeAuthSession(IAuthSession session, IAuthTokens tokens)
{
if (session.UserName.IsNullOrEmpty())
session.UserName = tokens.UserName;
if (session.DisplayName.IsNullOrEmpty())
session.DisplayName = tokens.DisplayName;
if (session.Email.IsNullOrEmpty())
session.Email = tokens.Email;
var oAuthTokens = session.GetAuthTokens(tokens.Provider);
if (oAuthTokens != null && oAuthTokens.UserId == tokens.UserId)
{
if (!oAuthTokens.UserName.IsNullOrEmpty())
session.UserName = oAuthTokens.UserName;
if (!oAuthTokens.DisplayName.IsNullOrEmpty())
session.DisplayName = oAuthTokens.DisplayName;
if (!oAuthTokens.Email.IsNullOrEmpty())
session.Email = oAuthTokens.Email;
if (!oAuthTokens.FirstName.IsNullOrEmpty())
session.FirstName = oAuthTokens.FirstName;
if (!oAuthTokens.LastName.IsNullOrEmpty())
session.LastName = oAuthTokens.LastName;
}
var key = tokens.Provider + ":" + (tokens.UserId ?? tokens.UserName);
return transientUserIdsMap.GetOrAdd(key,
k => Interlocked.Increment(ref transientUserAuthId)).ToString(CultureInfo.InvariantCulture);
}
protected virtual void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo) { }
protected static bool LoginMatchesSession(IAuthSession session, string userName)
{
if (session == null || userName == null) return false;
var isEmail = userName.Contains("@");
if (isEmail)
{
if (!userName.EqualsIgnoreCase(session.Email))
return false;
}
else
{
if (!userName.EqualsIgnoreCase(session.UserAuthName))
return false;
}
return true;
}
public Task<object> LogoutAsync(IServiceBase service, Authenticate request, CancellationToken token = default)
{
Logout(service, request);
return TypeConstants.EmptyTask;
}
public Task<object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
{
var response = Authenticate(authService, session, request);
return response.InTask();
}
public abstract bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null);
public abstract object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request);
public virtual Task OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes)
{
httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm));
return HostContext.AppHost.HandleShortCircuitedErrors(httpReq, httpRes, httpReq.Dto);
}
public static Task HandleFailedAuth(IAuthProvider authProvider,
IAuthSession session, IRequest httpReq, IResponse httpRes)
{
if (authProvider is AuthProvider baseAuthProvider)
return baseAuthProvider.OnFailedAuthentication(session, httpReq, httpRes);
httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
httpRes.AddHeader(HttpHeaders.WwwAuthenticate, $"{authProvider.Provider} realm=\"{authProvider.AuthRealm}\"");
return HostContext.AppHost.HandleShortCircuitedErrors(httpReq, httpRes, httpReq.Dto);
}
protected virtual bool UserNameAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null)
{
if (tokens?.UserName != null)
{
var userWithUserName = authRepo.GetUserAuthByUserName(tokens.UserName);
if (userWithUserName == null)
return false;
var isAnotherUser = userAuth == null || (userAuth.Id != userWithUserName.Id);
return isAnotherUser;
}
return false;
}
protected virtual bool EmailAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null)
{
if (tokens?.Email != null)
{
var userWithEmail = authRepo.GetUserAuthByUserName(tokens.Email);
if (userWithEmail == null)
return false;
var isAnotherUser = userAuth == null || (userAuth.Id != userWithEmail.Id);
return isAnotherUser;
}
return false;
}
protected virtual string GetAuthRedirectUrl(IServiceBase authService, IAuthSession session)
{
return session.ReferrerUrl;
}
public virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens=null)
{
if (AccountLockedValidator != null)
return AccountLockedValidator(authRepo, userAuth, tokens);
return userAuth?.LockedDate != null;
}
protected virtual IHttpResult ValidateAccount(IServiceBase authService, IAuthRepository authRepo, IAuthSession session, IAuthTokens tokens)
{
var userAuth = authRepo.GetUserAuth(session, tokens);
var authFeature = HostContext.GetPlugin<AuthFeature>();
if (authFeature != null && authFeature.ValidateUniqueUserNames && UserNameAlreadyExists(authRepo, userAuth, tokens))
{
return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "UserNameAlreadyExists")));
}
if (authFeature != null && authFeature.ValidateUniqueEmails && EmailAlreadyExists(authRepo, userAuth, tokens))
{
return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "EmailAlreadyExists")));
}
if (IsAccountLocked(authRepo, userAuth, tokens))
{
return authService.Redirect(FailedRedirectUrlFilter(this, GetReferrerUrl(authService, session).SetParam("f", "AccountLocked")));
}
return null;
}
protected virtual string GetReferrerUrl(IServiceBase authService, IAuthSession session, Authenticate request = null)
{
if (request == null)
request = authService.Request.Dto as Authenticate;
var referrerUrl = authService.Request.GetReturnUrl() ?? session.ReferrerUrl;
if (!string.IsNullOrEmpty(referrerUrl))
return referrerUrl;
referrerUrl = authService.Request.GetHeader("Referer");
if (!string.IsNullOrEmpty(referrerUrl))
return referrerUrl;
var requestUri = authService.Request.AbsoluteUri;
if (requestUri.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0)
{
referrerUrl = this.RedirectUrl
?? authService.Request.GetBaseUrl()
?? requestUri.InferBaseUrl();
}
return referrerUrl;
}
protected virtual object ConvertToClientError(object failedResult, bool isHtml)
{
if (!isHtml)
{
if (failedResult is IHttpResult httpRes)
{
if (httpRes.Headers.TryGetValue(HttpHeaders.Location, out var location))
{
var parts = location.SplitOnLast("f=");
if (parts.Length == 2)
{
return new HttpError(HttpStatusCode.BadRequest, parts[1], parts[1].SplitCamelCase());
}
}
}
}
return failedResult;
}
public virtual void Register(IAppHost appHost, AuthFeature feature)
{
RestoreSessionFromState ??= appHost.Config.UseSameSiteCookies == true;
}
}
}