public static async Task <bool> AuthenticateAsync(IRequest req, object requestDto = null, IAuthSession session = null, IAuthProvider[] authProviders = null) { if (HostContext.HasValidAuthSecret(req)) { return(true); } session ??= await(req ?? throw new ArgumentNullException(nameof(req))).GetSessionAsync().ConfigAwait(); authProviders ??= AuthenticateService.GetAuthProviders(); var authValidate = HostContext.GetPlugin <AuthFeature>()?.OnAuthenticateValidate; var ret = authValidate?.Invoke(req); if (ret != null) { return(false); } req.PopulateFromRequestIfHasSessionId(requestDto); if (!req.Items.ContainsKey(Keywords.HasPreAuthenticated)) { //Unauthorized or invalid requests will terminate the response and return false var mockResponse = new BasicRequest().Response; req.Items[Keywords.HasPreAuthenticated] = true; foreach (var authWithRequest in authProviders.OfType <IAuthWithRequest>()) { await authWithRequest.PreAuthenticateAsync(req, mockResponse).ConfigAwait(); if (mockResponse.IsClosed) { return(false); } } foreach (var authWithRequest in authProviders.OfType <IAuthWithRequestSync>()) { authWithRequest.PreAuthenticate(req, mockResponse); if (mockResponse.IsClosed) { return(false); } } } var sessionIsAuthenticated = session != null && (authProviders.Length > 0 ? authProviders.Any(x => session.IsAuthorized(x.Provider)) : session.IsAuthenticated); return(sessionIsAuthenticated); }
public static bool IsAuthenticated(this IRequest req) { //Sync with [Authenticate] impl if (HostContext.HasValidAuthSecret(req)) { return(true); } var authProviders = AuthenticateService.GetAuthProviders(); AuthenticateAttribute.PreAuthenticate(req, authProviders); var session = req.GetSession(); return(session != null && authProviders.Any(x => session.IsAuthorized(x.Provider))); }
public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto) { if (AuthenticateService.AuthProviders == null) { throw new InvalidOperationException( "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute"); } if (HostContext.HasValidAuthSecret(req)) { return; } var authProviders = AuthenticateService.GetAuthProviders(this.Provider); if (authProviders.Length == 0) { await res.WriteError(req, requestDto, $"No registered Auth Providers found matching {this.Provider ?? "any"} provider").ConfigAwait(); res.EndRequest(); return; } req.PopulateFromRequestIfHasSessionId(requestDto); await PreAuthenticateAsync(req, authProviders).ConfigAwait(); if (res.IsClosed) { return; } var session = req.GetSession(); if (session == null || !authProviders.Any(x => session.IsAuthorized(x.Provider))) { if (this.DoHtmlRedirectIfConfigured(req, res, true)) { return; } await AuthProvider.HandleFailedAuth(authProviders[0], session, req, res).ConfigAwait(); } }
public virtual string GetConsumerId(IRequest request) { if (AuthenticateService.GetAuthProviders() == null) { throw new InvalidOperationException( "AuthService not initialized. This is required for generating default ConsumerId for RateLimitting."); } IAuthSession userSession = request.GetSession(); // TODO This will need more love to authorize user rather than just verify authentication (not necessarily here but in general) if (!IsUserAuthenticated(userSession)) { log.Error($"User {userSession?.UserName ?? "<unknown>"} not authenticated for request {request.AbsoluteUri}"); throw new AuthenticationException("You must be authenticated to access this service"); } return(userSession.UserAuthId?.ToLowerInvariant()); }
public void Register(IAppHost appHost) { hasRegistered = true; AuthenticateService.Init(sessionFactory, AuthProviders); var unitTest = appHost == null; if (unitTest) { return; } if (HostContext.StrictMode) { var sessionInstance = sessionFactory(); if (TypeSerializer.HasCircularReferences(sessionInstance)) { throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory", StrictModeCodes.CyclicalUserSession); } } appHost.RegisterServices(ServiceRoutes); var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First(); sessionFeature.SessionExpiry = SessionExpiry; sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry; appHost.LoadPlugin(RegisterPlugins.ToArray()); if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null) { appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider()); } AuthProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this)); AuthenticateService.HtmlRedirect = HtmlRedirect; AuthenticateService.HtmlRedirectAccessDenied = HtmlRedirectAccessDenied; AuthenticateService.HtmlRedirectReturnParam = HtmlRedirectReturnParam; AuthenticateService.HtmlRedirectReturnPathOnly = HtmlRedirectReturnPathOnly; AuthenticateService.AuthResponseDecorator = AuthResponseDecorator; if (ValidateFn != null) { AuthenticateService.ValidateFn = ValidateFn; } var authNavItems = AuthProviders.Select(x => (x as AuthProvider)?.NavItem).Where(x => x != null); if (!ViewUtils.NavItemsMap.TryGetValue("auth", out var navItems)) { ViewUtils.NavItemsMap["auth"] = navItems = new List <NavItem>(); } var isDefaultHtmlRedirect = HtmlRedirect == "~/" + LocalizedStrings.Login.Localize(); if (IncludeDefaultLogin && isDefaultHtmlRedirect && !appHost.VirtualFileSources.FileExists("/login.html")) { appHost.VirtualFileSources.GetMemoryVirtualFiles().WriteFile("/login.html", Templates.HtmlTemplates.GetLoginTemplate()); } navItems.AddRange(authNavItems); appHost.AddToAppMetadata(meta => { meta.Plugins.Auth = new AuthInfo { HasAuthSecret = (appHost.Config.AdminAuthSecret != null).NullIfFalse(), HasAuthRepository = appHost.GetContainer().Exists <IAuthRepository>().NullIfFalse(), IncludesRoles = IncludeRolesInAuthenticateResponse.NullIfFalse(), IncludesOAuthTokens = IncludeOAuthTokensInAuthenticateResponse.NullIfFalse(), HtmlRedirect = HtmlRedirect?.TrimStart('~'), AuthProviders = AuthenticateService.GetAuthProviders().Map(x => new MetaAuthProvider { Type = x.Type, Name = x.Provider, NavItem = (x as AuthProvider)?.NavItem, Meta = x.Meta, }) }; }); }
public void Configure(IAppHost appHost) { var AppSettings = appHost.AppSettings; appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new ApiKeyAuthProvider(AppSettings) { KeyTypes = new[] { "secret", "publishable" }, }, new NetCoreIdentityAuthProvider(AppSettings) // Adapter to enable ServiceStack Auth in MVC { AdminRoles = { "Manager" }, // Automatically Assign additional roles to Admin Users CreateClaimsPrincipal = (claims, session, req) => { var apiRepo = (IManageApiKeys)HostContext.TryResolve <IAuthRepository>(); var apiKeys = apiRepo.GetUserApiKeys(session.UserAuthId); var apiKey = apiKeys.First(k => k.KeyType == "publishable" && k.Environment == "live"); claims.Add(new Claim("ApiKey", apiKey.Id)); var identity = new ClaimsIdentity(claims, "Identity.Application"); return(new ClaimsPrincipal(identity)); } }, new CredentialsAuthProvider(AppSettings), // Sign In with Username / Password credentials new FacebookAuthProvider(AppSettings), // Create App at: https://developers.facebook.com/apps new TwitterAuthProvider(AppSettings), // Create App at: https://dev.twitter.com/apps new GoogleAuthProvider(AppSettings), // https://console.developers.google.com/apis/credentials new MicrosoftGraphAuthProvider(AppSettings), // Create App https://apps.dev.microsoft.com })); appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service //override the default registration validation with your own custom implementation appHost.RegisterAs <CustomRegistrationValidator, IValidator <Register> >(); appHost.AfterInitCallbacks.Add(host => { try { var authProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProviders() .First(x => x is ApiKeyAuthProvider); using (var db = host.TryResolve <IDbConnectionFactory>().Open()) { var userWithKeysIds = db.Column <string>(db.From <ApiKey>() .SelectDistinct(x => x.UserAuthId)).Map(int.Parse); var userIdsMissingKeys = db.Column <string>(db.From <AppUser>() .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id)) .Select(x => x.Id)); var authRepo = (IManageApiKeys)host.TryResolve <IAuthRepository>(); foreach (var userId in userIdsMissingKeys) { var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString()); authRepo.StoreAll(apiKeys); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }); }