static IAppHost GetAppHost()
 {
     if (_appHost == null)
     {
         _appHost = new BasicAppHost();
         var authService = new AuthenticateService();
         authService.SetResolver(_appHost);
         _appHost.Container.Register(authService);
         _appHost.Container.Register<IAuthSession>(authUserSession);
     }
     return _appHost;
 }
Ejemplo n.º 2
0
 public void TestFixtureSetUp()
 {
     appHost = new BasicAppHost
     {
         ConfigureContainer = c =>
         {
             var authService = new AuthenticateService();
             c.Register(authService);
             c.Register<IAuthSession>(authUserSession);
             AuthenticateService.Init(() => authUserSession, new CredentialsAuthProvider());
         }
     }.Init();
 }
Ejemplo n.º 3
0
        public object Any(ConvertSessionToToken request)
        {
            var jwtAuthProvider = (JwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider();

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request));
            }

            if (Request.ResponseContentType.MatchesContentType(MimeTypes.Html))
            {
                Request.ResponseContentType = MimeTypes.Json;
            }

            var token = Request.GetJwtToken();

            if (string.IsNullOrEmpty(token))
            {
                var session = Request.GetSession();
                token = jwtAuthProvider.CreateJwtBearerToken(Request, session);

                if (!request.PreserveSession)
                {
                    Request.RemoveSession(session.Id);
                }
            }

            return(new HttpResult(new ConvertSessionToTokenResponse {
                AccessToken = jwtAuthProvider.IncludeJwtInConvertSessionToTokenResponse
                    ? token
                    : null
            })
            {
                Cookies =
                {
                    new Cookie(Keywords.TokenCookie, token, Cookies.RootPath)
                    {
                        HttpOnly = true,
                        Secure = Request.IsSecureConnection,
                        Expires = DateTime.UtcNow.Add(jwtAuthProvider.ExpireTokensIn),
                    }
                }
            });
        }
Ejemplo n.º 4
0
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var userSession = session as AuthUserSession;

            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve <IAuthRepository>();

            if (authRepo != null)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null)
                    {
                        continue;
                    }
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }
            }

            authService.SaveSession(session, SessionExpiry);
            session.OnAuthenticated(authService, session, tokens, authInfo);
        }
Ejemplo n.º 5
0
        public object Any(ConvertSessionToToken request)
        {
            var jwtAuthProvider = AuthenticateService.GetAuthProvider(JwtAuthProvider.Name) as JwtAuthProvider;

            if (jwtAuthProvider == null)
            {
                throw new NotSupportedException("JwtAuthProvider is not registered");
            }

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
            }

            var session = Request.GetSession();

            if (session.FromToken)
            {
                return(new ConvertSessionToTokenResponse());
            }

            var token = jwtAuthProvider.CreateJwtBearerToken(session);

            if (!request.PreserveSession)
            {
                Request.RemoveSession(session.Id);
            }

            return(new HttpResult(new ConvertSessionToTokenResponse())
            {
                Cookies =
                {
                    new Cookie(Keywords.TokenCookie, token, Cookies.RootPath)
                    {
                        HttpOnly = true,
                        Secure = Request.IsSecureConnection,
                        Expires = DateTime.UtcNow.Add(jwtAuthProvider.ExpireTokensIn),
                    }
                }
            });
        }
Ejemplo n.º 6
0
        protected virtual bool EnableRefreshToken()
        {
            var userSessionSource = AuthenticateService.GetUserSessionSource();

            if (userSessionSource != null)
            {
                return(true);
            }

            var authRepo = HostContext.AppHost?.TryResolve <IAuthRepository>();

            if (authRepo == null)
            {
                return(false);
            }

            using (authRepo as IDisposable)
            {
                return(authRepo is IUserAuthRepository);
            }
        }
Ejemplo n.º 7
0
        public async Task <object> Any(GetAccessToken request)
        {
            var jwtAuthProvider = (JwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider();

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request));
            }

            var refreshTokenCookie = Request.Cookies.TryGetValue(Keywords.RefreshTokenCookie, out var refTok)
                ? refTok.Value
                : null;

            var refreshToken = request.RefreshToken ?? refreshTokenCookie;
            var accessToken  = await jwtAuthProvider.CreateAccessTokenFromRefreshToken(refreshToken, Request).ConfigAwait();

            var response = new GetAccessTokenResponse
            {
                AccessToken = accessToken
            };

            // Don't return JWT in Response Body if Refresh Token Cookie was used
            if (refreshTokenCookie == null && jwtAuthProvider.UseTokenCookie != true)
            {
                return(response);
            }

            var httpResult = new HttpResult(new GetAccessTokenResponse())
                             .AddCookie(Request,
                                        new Cookie(Keywords.TokenCookie, accessToken, Cookies.RootPath)
            {
                HttpOnly = true,
                Secure   = Request.IsSecureConnection,
                Expires  = DateTime.UtcNow.Add(jwtAuthProvider.ExpireTokensIn),
            });

            return(httpResult);
        }
Ejemplo n.º 8
0
        /// <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.ProviderOAuthAccess)
            {
                var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                if (authProvider == null)
                {
                    continue;
                }
                var userAuthProvider = authProvider as OAuthProvider;
                if (userAuthProvider != null)
                {
                    userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                }
            }

            authRepo.SaveUserAuth(session);

            var httpRes = authService.Request.Response as IHttpResponse;

            if (httpRes != null)
            {
                httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
            }
            OnSaveUserAuth(authService, session);
        }
Ejemplo n.º 9
0
        public override async Task <IHttpResult> OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            session.AuthProvider = Name;
            if (session is AuthUserSession userSession)
            {
                await LoadUserAuthInfoAsync(userSession, tokens, authInfo, token).ConfigAwait();

                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            if (session is IAuthSessionExtended authSession)
            {
                var failed = authSession.Validate(authService, session, tokens, authInfo)
                             ?? await authSession.ValidateAsync(authService, session, tokens, authInfo, token)
                             ?? AuthEvents.Validate(authService, session, tokens, authInfo)
                             ?? (AuthEvents is IAuthEventsAsync asyncEvents
                        ? await asyncEvents.ValidateAsync(authService, session, tokens, authInfo, token)
                        : null);

                if (failed != null)
                {
                    await authService.RemoveSessionAsync(token).ConfigAwait();

                    return(failed);
                }
            }

            var authRepo = GetUserAuthRepositoryAsync(authService.Request);

#if NET472 || NETSTANDARD2_0
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = (await authRepo.CreateOrMergeAuthSessionAsync(session, tokens, token)).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = await ValidateAccountAsync(authService, authRepo, session, tokens, token).ConfigAwait();

                    if (failed != null)
                    {
                        return(failed);
                    }
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                if (session is IAuthSessionExtended sessionExt)
                {
                    await sessionExt.OnAuthenticatedAsync(authService, session, tokens, authInfo, token).ConfigAwait();
                }
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
                if (AuthEvents is IAuthEventsAsync asyncEvents)
                {
                    await asyncEvents.OnAuthenticatedAsync(authService.Request, session, authService, tokens, authInfo, token).ConfigAwait();
                }
            }
            finally
            {
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
Ejemplo n.º 10
0
        public object Any(GetAccessToken request)
        {
            var jwtAuthProvider = AuthenticateService.GetAuthProvider(JwtAuthProvider.Name) as JwtAuthProvider;

            if (jwtAuthProvider == null)
            {
                throw new NotSupportedException("JwtAuthProvider is not registered");
            }

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
            }

            if (string.IsNullOrEmpty(request.RefreshToken))
            {
                throw new ArgumentNullException(nameof(request.RefreshToken));
            }

            var userRepo = AuthRepository as IUserAuthRepository;

            if (userRepo == null)
            {
                throw new NotSupportedException("JWT Refresh Tokens requires a registered IUserAuthRepository");
            }

            var jwtPayload = jwtAuthProvider.GetVerifiedJwtPayload(request.RefreshToken.Split('.'));

            jwtAuthProvider.AssertJwtPayloadIsValid(jwtPayload);

            if (jwtAuthProvider.ValidateRefreshToken != null && !jwtAuthProvider.ValidateRefreshToken(jwtPayload, Request))
            {
                throw new ArgumentException(ErrorMessages.RefreshTokenInvalid, nameof(request.RefreshToken));
            }

            var userId = jwtPayload["sub"];

            var userAuth = userRepo.GetUserAuth(userId);

            if (userAuth == null)
            {
                throw HttpError.NotFound(ErrorMessages.UserNotExists);
            }

            if (jwtAuthProvider.IsAccountLocked(userRepo, userAuth))
            {
                throw new AuthenticationException(ErrorMessages.UserAccountLocked);
            }

            var session = SessionFeature.CreateNewSession(Request, SessionExtensions.CreateRandomSessionId());

            jwtAuthProvider.PopulateSession(userRepo, userAuth, session);

            IEnumerable <string> roles = null, perms = null;
            var manageRoles = userRepo as IManageRoles;

            if (manageRoles != null && session.UserAuthId != null)
            {
                roles = manageRoles.GetRoles(session.UserAuthId);
                perms = manageRoles.GetPermissions(session.UserAuthId);
            }

            var accessToken = jwtAuthProvider.CreateJwtBearerToken(session, roles, perms);

            return(new GetAccessTokenResponse
            {
                AccessToken = accessToken
            });
        }
Ejemplo n.º 11
0
        public async Task <object> Any(GetAccessToken request)
        {
            var jwtAuthProvider = (JwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider();

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request));
            }

            if (string.IsNullOrEmpty(request.RefreshToken))
            {
                throw new ArgumentNullException(nameof(request.RefreshToken));
            }

            JsonObject jwtPayload;

            try
            {
                jwtPayload = jwtAuthProvider.GetVerifiedJwtPayload(Request, request.RefreshToken.Split('.'));
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }

            if (jwtPayload == null)
            {
                throw new ArgumentException(ErrorMessages.TokenInvalid.Localize(Request));
            }

            jwtAuthProvider.AssertJwtPayloadIsValid(jwtPayload);

            if (jwtAuthProvider.ValidateRefreshToken != null && !jwtAuthProvider.ValidateRefreshToken(jwtPayload, Request))
            {
                throw new ArgumentException(ErrorMessages.RefreshTokenInvalid.Localize(Request), nameof(request.RefreshToken));
            }

            var userId = jwtPayload["sub"];

            var result = await Request.GetSessionFromSourceAsync(userId, async (authRepo, userAuth) => {
                if (await jwtAuthProvider.IsAccountLockedAsync(authRepo, userAuth))
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(Request));
                }
            }).ConfigAwait();

            if (result == null)
            {
                throw new NotSupportedException("JWT RefreshTokens requires a registered IUserAuthRepository or an AuthProvider implementing IUserSessionSource");
            }

            var accessToken = jwtAuthProvider.CreateJwtBearerToken(Request,
                                                                   session: result.Session, roles: result.Roles, perms: result.Permissions);

            var response = new GetAccessTokenResponse
            {
                AccessToken = accessToken
            };

            if (request.UseTokenCookie.GetValueOrDefault(jwtAuthProvider.UseTokenCookie) != true)
            {
                return(response);
            }

            return(new HttpResult(new GetAccessTokenResponse())
            {
                Cookies =
                {
                    new Cookie(Keywords.TokenCookie, accessToken, Cookies.RootPath)
                    {
                        HttpOnly = true,
                        Secure = Request.IsSecureConnection,
                        Expires = DateTime.UtcNow.Add(jwtAuthProvider.ExpireTokensIn),
                    }
                }
            });
        }
Ejemplo n.º 12
0
        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>();
                }

                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);
        }
		public static RegisterService GetRegistrationService(
			IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
			MockRequestContext requestContext = null)
		{
			if (requestContext == null)
				requestContext = new MockRequestContext();
			if (oAuthUserSession == null)
				oAuthUserSession = requestContext.ReloadSession();

			var httpReq = requestContext.Get<IHttpRequest>();
			var httpRes = requestContext.Get<IHttpResponse>();
			oAuthUserSession.Id = httpRes.CreateSessionId(httpReq);
			httpReq.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost {
				Container = requestContext.Container
			};

			requestContext.Container.Register(userAuthRepository);

		    var authService = new AuthenticateService {
                RequestContext = requestContext,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				UserAuthRepo = userAuthRepository,
				RequestContext = requestContext,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
Ejemplo n.º 14
0
        public virtual async Task <IHttpResult> OnAuthenticatedAsync(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo, CancellationToken token = default)
        {
            session.AuthProvider = Provider;

            if (session is AuthUserSession userSession)
            {
                await LoadUserAuthInfoAsync(userSession, tokens, authInfo, token).ConfigAwait();

                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)
                {
                    await authService.RemoveSessionAsync(token).ConfigAwait();

                    return(failed);
                }
            }

            var authRepo = GetAuthRepositoryAsync(authService.Request);

#if NET472 || NETSTANDARD2_0
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                if (CustomValidationFilter != null)
                {
                    var ctx = new AuthContext
                    {
                        Request             = authService.Request,
                        Service             = authService,
                        AuthProvider        = this,
                        Session             = session,
                        AuthTokens          = tokens,
                        AuthInfo            = authInfo,
                        AuthRepositoryAsync = authRepo,
                        AuthRepository      = authRepo as IAuthRepository,
                    };
                    var response = CustomValidationFilter(ctx);
                    if (response != null)
                    {
                        await authService.RemoveSessionAsync(token).ConfigAwait();

                        return(response);
                    }
                }

                if (authRepo != null)
                {
                    var failed = await ValidateAccountAsync(authService, authRepo, session, tokens, token).ConfigAwait();

                    if (failed != null)
                    {
                        await authService.RemoveSessionAsync(token).ConfigAwait();

                        return(failed);
                    }

                    if (hasTokens)
                    {
                        var authDetails = await authRepo.CreateOrMergeAuthSessionAsync(session, tokens, token).ConfigAwait();

                        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);
                        }
                    }

                    await authRepo.LoadUserAuthAsync(session, tokens, token).ConfigAwait();

                    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
            {
                await this.SaveSessionAsync(authService, session, SessionExpiry, token).ConfigAwait();

                authService.Request.Items[Keywords.DidAuthenticate] = true;
            }

            return(null);
        }
		public static RegisterService GetRegistrationService(
            IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
            BasicRequest request = null)
		{
			if (request == null)
                request = new BasicRequest();
			if (oAuthUserSession == null)
				oAuthUserSession = request.ReloadSession();

            oAuthUserSession.Id = request.Response.CreateSessionId(request);
            request.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost();

            mockAppHost.Container.Register<IAuthRepository>(userAuthRepository);

		    var authService = new AuthenticateService {
                Request = request,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegisterService {
				AuthRepo = userAuthRepository,
				Request = request,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
Ejemplo n.º 16
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var userSession = session as AuthUserSession;

            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);

                if (LoadUserAuthFilter != null)
                {
                    LoadUserAuthFilter(userSession, tokens, authInfo);
                }
            }

            var authRepo = authService.TryResolve <IAuthRepository>();

            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)
            {
                if (tokens != null)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                }

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null)
                    {
                        continue;
                    }
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }

                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                {
                    return(failed);
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
                AuthEvents.OnAuthenticated(authService.Request, session, authService, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return(null);
        }
Ejemplo n.º 17
0
        public virtual IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var userSession = session as AuthUserSession;

            if (userSession != null)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
            }

            var authRepo = authService.TryResolve <IAuthRepository>();

            if (authRepo != null)
            {
                var hasTokens = tokens != null;
                if (hasTokens)
                {
                    authInfo.ForEach((x, y) => tokens.Items[x] = y);
                }

                var failed = ValidateAccount(authService, authRepo, session, tokens);
                if (failed != null)
                {
                    return(failed);
                }

                if (hasTokens)
                {
                    session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
                }

                authRepo.LoadUserAuth(session, tokens);

                foreach (var oAuthToken in session.ProviderOAuthAccess)
                {
                    var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);
                    if (authProvider == null)
                    {
                        continue;
                    }
                    var userAuthProvider = authProvider as OAuthProvider;
                    if (userAuthProvider != null)
                    {
                        userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
                    }
                }

                var httpRes = authService.Request.Response as IHttpResponse;
                if (httpRes != null)
                {
                    httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
                }
            }

            try
            {
                session.IsAuthenticated = true;
                session.OnAuthenticated(authService, session, tokens, authInfo);
            }
            finally
            {
                authService.SaveSession(session, SessionExpiry);
            }

            return(null);
        }
Ejemplo n.º 18
0
        public static void AuthenticateIfWindowsAuth(IRequest req, IResponse res)
        {
            var winAuthProvider = AuthenticateService.GetAuthProvider(Name) as AspNetWindowsAuthProvider;

            winAuthProvider?.IsAuthorized(req.GetUser());
        }
Ejemplo n.º 19
0
        public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            session.AuthProvider = Name;
            if (session is AuthUserSession userSession)
            {
                LoadUserAuthInfo(userSession, tokens, authInfo);
                HostContext.TryResolve <IAuthMetadataProvider>().SafeAddMetadata(tokens, authInfo);
            }

            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 = HostContext.AppHost.GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                if (authRepo != null)
                {
                    if (tokens != null)
                    {
                        authInfo.ForEach((x, y) => tokens.Items[x] = y);
                        session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens).UserAuthId.ToString();
                    }

                    foreach (var oAuthToken in session.GetAuthTokens())
                    {
                        var authProvider = AuthenticateService.GetAuthProvider(oAuthToken.Provider);

                        var userAuthProvider = authProvider as OAuthProvider;
                        userAuthProvider?.LoadUserOAuthProvider(session, oAuthToken);
                    }

                    var failed = ValidateAccount(authService, authRepo, session, tokens);
                    if (failed != null)
                    {
                        return(failed);
                    }
                }
            }

            try
            {
                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);
        }
Ejemplo n.º 20
0
        public object Any(GetAccessToken request)
        {
            var jwtAuthProvider = (JwtAuthProvider)AuthenticateService.GetRequiredJwtAuthProvider();

            if (jwtAuthProvider.RequireSecureConnection && !Request.IsSecureConnection)
            {
                throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection.Localize(Request));
            }

            if (string.IsNullOrEmpty(request.RefreshToken))
            {
                throw new ArgumentNullException(nameof(request.RefreshToken));
            }

            JsonObject jwtPayload;

            try
            {
                jwtPayload = jwtAuthProvider.GetVerifiedJwtPayload(Request, request.RefreshToken.Split('.'));
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }

            jwtAuthProvider.AssertJwtPayloadIsValid(jwtPayload);

            if (jwtAuthProvider.ValidateRefreshToken != null && !jwtAuthProvider.ValidateRefreshToken(jwtPayload, Request))
            {
                throw new ArgumentException(ErrorMessages.RefreshTokenInvalid.Localize(Request), nameof(request.RefreshToken));
            }

            var userId = jwtPayload["sub"];

            IAuthSession         session;
            IEnumerable <string> roles = null, perms = null;

            var userSessionSource = AuthenticateService.GetUserSessionSource();

            if (userSessionSource != null)
            {
                session = userSessionSource.GetUserSession(userId);
                if (session == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                roles = session.Roles;
                perms = session.Permissions;
            }
            else if (AuthRepository is IUserAuthRepository userRepo)
            {
                var userAuth = userRepo.GetUserAuth(userId);
                if (userAuth == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                if (jwtAuthProvider.IsAccountLocked(userRepo, userAuth))
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(Request));
                }

                session = SessionFeature.CreateNewSession(Request, SessionExtensions.CreateRandomSessionId());
                session.PopulateSession(userAuth, userRepo);

                if (userRepo is IManageRoles manageRoles && session.UserAuthId != null)
                {
                    roles = manageRoles.GetRoles(session.UserAuthId);
                    perms = manageRoles.GetPermissions(session.UserAuthId);
                }
            }
            else
            {
                throw new NotSupportedException("JWT RefreshTokens requires a registered IUserAuthRepository or an AuthProvider implementing IUserSessionSource");
            }

            var accessToken = jwtAuthProvider.CreateJwtBearerToken(Request, session, roles, perms);

            var response = new GetAccessTokenResponse
            {
                AccessToken = accessToken
            };

            if (request.UseTokenCookie != true)
            {
                return(response);
            }

            return(new HttpResult(new GetAccessTokenResponse())
            {
                Cookies =
                {
                    new Cookie(Keywords.TokenCookie, accessToken, Cookies.RootPath)
                    {
                        HttpOnly = true,
                        Secure = Request.IsSecureConnection,
                        Expires = DateTime.UtcNow.Add(jwtAuthProvider.ExpireTokensIn),
                    }
                }
            });
        }
Ejemplo n.º 21
0
        public virtual bool IsAuthorized(string provider)
        {
            var tokens = ProviderOAuthAccess.FirstOrDefault(x => x.Provider == provider);

            return(AuthenticateService.GetAuthProvider(provider).IsAuthorizedSafe(this, tokens));
        }