/
AuthProvider.cs
507 lines (428 loc) · 20.2 KB
/
AuthProvider.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Web;
namespace ServiceStack.Auth
{
public abstract class AuthProvider : IAuthProvider
{
protected static readonly ILog Log = LogManager.GetLogger(typeof(AuthProvider));
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 Action<AuthUserSession, IAuthTokens, Dictionary<string, string>> LoadUserAuthFilter { get; set; }
public Func<AuthContext, IHttpResult> CustomValidationFilter { get; set; }
public Func<AuthProvider, string, string> PreAuthUrlFilter = UrlFilter;
public Func<AuthProvider, string, string> AccessTokenUrlFilter = UrlFilter;
public Func<AuthProvider, string, string> SuccessRedirectUrlFilter = UrlFilter;
public Func<AuthProvider, string, string> FailedRedirectUrlFilter = UrlFilter;
public Func<AuthProvider, string, string> LogoutUrlFilter = UrlFilter;
public static string UrlFilter(AuthProvider provider, string url)
{
return url;
}
protected AuthProvider()
{
PersistSession = !GetType().HasInterface(typeof(IAuthWithRequest));
}
protected AuthProvider(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 = request?.Continue
?? (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.SetParam("s", "-1")));
return new AuthenticateResponse();
}
/// <summary>
/// Saves the Auth Tokens for this request. Called in OnAuthenticated().
/// Overrideable, the default behaviour is to call IUserAuthRepository.CreateOrMergeAuthSession().
/// </summary>
protected virtual void SaveUserAuth(IServiceBase authService, IAuthSession session, IAuthRepository authRepo, IAuthTokens tokens)
{
if (authRepo == null) return;
if (tokens != null)
{
session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
}
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);
}
authRepo.SaveUserAuth(session);
var httpRes = authService.Request.Response as IHttpResponse;
httpRes?.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
OnSaveUserAuth(authService, session);
}
public virtual void OnSaveUserAuth(IServiceBase authService, IAuthSession session) { }
public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
session.AuthProvider = Provider;
var userSession = session as AuthUserSession;
if (userSession != null)
{
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>();
authInfo.ForEach((x, y) => tokens.Items[x] = y);
}
var authRepo = GetAuthRepository(authService.Request);
using (authRepo as IDisposable)
{
if (CustomValidationFilter != null)
{
var ctx = new AuthContext
{
Request = authService.Request,
Service = authService,
AuthProvider = 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
{
this.SaveSession(authService, session, SessionExpiry);
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 abstract bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null);
public abstract object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request);
public virtual void OnFailedAuthentication(IAuthSession session, IRequest httpReq, IResponse httpRes)
{
httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm));
httpRes.EndRequest();
}
public static void HandleFailedAuth(IAuthProvider authProvider,
IAuthSession session, IRequest httpReq, IResponse httpRes)
{
var baseAuthProvider = authProvider as AuthProvider;
if (baseAuthProvider != null)
{
baseAuthProvider.OnFailedAuthentication(session, httpReq, httpRes);
return;
}
httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
httpRes.AddHeader(HttpHeaders.WwwAuthenticate, $"{authProvider.Provider} realm=\"{authProvider.AuthRealm}\"");
httpRes.EndRequest();
}
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;
}
internal virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens=null)
{
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 = session.ReferrerUrl;
if (referrerUrl.IsNullOrEmpty())
referrerUrl = request?.Continue
?? authService.Request.GetHeader("Referer");
var requestUri = authService.Request.AbsoluteUri;
if (referrerUrl.IsNullOrEmpty()
|| referrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0)
referrerUrl = this.RedirectUrl
?? authService.Request.GetBaseUrl()
?? requestUri.InferBaseUrl();
return referrerUrl;
}
internal void PopulateSession(IUserAuthRepository authRepo, IUserAuth userAuth, IAuthSession session)
{
if (authRepo == null)
return;
var holdSessionId = session.Id;
session.PopulateWith(userAuth); //overwrites session.Id
session.Id = holdSessionId;
session.IsAuthenticated = true;
session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
session.ProviderOAuthAccess = authRepo.GetUserAuthDetails(session.UserAuthId)
.ConvertAll(x => (IAuthTokens)x);
}
protected virtual object ConvertToClientError(object failedResult, bool isHtml)
{
if (!isHtml)
{
var httpRes = failedResult as IHttpResult;
if (httpRes != null)
{
string location;
if (httpRes.Headers.TryGetValue(HttpHeaders.Location, out location))
{
var parts = location.SplitOnLast("f=");
if (parts.Length == 2)
{
return new HttpError(HttpStatusCode.BadRequest, parts[1], parts[1].SplitCamelCase());
}
}
}
}
return failedResult;
}
}
public class AuthContext
{
public IRequest Request { get; set; }
public IServiceBase Service { get; set; }
public AuthProvider AuthProvider { get; set; }
public IAuthSession Session { get; set; }
public IAuthTokens AuthTokens { get; set; }
public Dictionary<string, string> AuthInfo { get; set; }
public IAuthRepository AuthRepository { get; set; }
}
public static class AuthExtensions
{
public static bool IsAuthorizedSafe(this IAuthProvider authProvider, IAuthSession session, IAuthTokens tokens)
{
return authProvider != null && authProvider.IsAuthorized(session, tokens);
}
public static string SanitizeOAuthUrl(this string url)
{
return (url ?? "").Replace("\\/", "/");
}
internal static bool PopulateFromRequestIfHasSessionId(this IRequest req, object requestDto)
{
var hasSession = requestDto as IHasSessionId;
if (hasSession?.SessionId != null)
{
req.SetSessionId(hasSession.SessionId);
return true;
}
return false;
}
internal static string NotLogoutUrl(this string url)
{
return url == null || url.EndsWith("/auth/logout")
? null
: url;
}
public static void SaveSession(this IAuthProvider provider, IServiceBase authService, IAuthSession session, TimeSpan? sessionExpiry = null)
{
var authProvider = provider as AuthProvider;
var persistSession = authProvider == null || authProvider.PersistSession;
if (persistSession)
{
authService.SaveSession(session, sessionExpiry);
}
else
{
authService.Request.Items[Keywords.Session] = session;
}
}
}
}