Search in sources :

Example 31 with SessionId

use of org.gluu.oxauth.model.common.SessionId in project oxAuth by GluuFederation.

the class MTLSService method authenticatedSuccessfully.

private void authenticatedSuccessfully(Client client, HttpServletRequest httpRequest) {
    authenticator.configureSessionClient(client);
    List<Prompt> prompts = Prompt.fromString(httpRequest.getParameter(AuthorizeRequestParam.PROMPT), " ");
    if (prompts.contains(Prompt.LOGIN)) {
        // skip session authentication if we have prompt=login
        return;
    }
    SessionId sessionIdObject = sessionIdService.getSessionId(httpRequest);
    if (sessionIdObject == null || sessionIdObject.getState() != SessionIdState.AUTHENTICATED) {
        return;
    }
    authenticator.authenticateBySessionId(sessionIdObject);
}
Also used : Prompt(org.gluu.oxauth.model.common.Prompt) SessionId(org.gluu.oxauth.model.common.SessionId)

Example 32 with SessionId

use of org.gluu.oxauth.model.common.SessionId in project oxAuth by GluuFederation.

the class Authenticator method userAuthenticationInteractive.

private String userAuthenticationInteractive(HttpServletRequest servletRequest) {
    SessionId sessionId = getSessionId(servletRequest);
    Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
    if (sessionIdAttributes == null) {
        logger.debug("Unable to get session attributes. SessionId: " + (sessionId != null ? sessionId.getId() : null));
        return Constants.RESULT_EXPIRED;
    }
    // Set current state into identity to allow use in login form and
    // authentication scripts
    identity.setSessionId(sessionId);
    initCustomAuthenticatorVariables(sessionIdAttributes);
    boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
    if (useExternalAuthenticator && !StringHelper.isEmpty(this.authAcr)) {
        initCustomAuthenticatorVariables(sessionIdAttributes);
        if ((this.authStep == null) || StringHelper.isEmpty(this.authAcr)) {
            logger.error("Failed to determine authentication mode");
            return Constants.RESULT_EXPIRED;
        }
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
        if (customScriptConfiguration == null) {
            logger.error("Failed to get CustomScriptConfiguration for acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return Constants.RESULT_FAILURE;
        }
        // Check if all previous steps had passed
        boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep);
        if (!passedPreviousSteps) {
            logger.error("There are authentication steps not marked as passed. acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return Constants.RESULT_FAILURE;
        }
        // Restore identity working parameters from session
        setIdentityWorkingParameters(sessionIdAttributes);
        boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
        if (logger.isDebugEnabled()) {
            String userId = credentials.getUsername();
            if (StringHelper.isEmpty(userId)) {
                User user = identity.getUser();
                if (user != null) {
                    userId = user.getUserId();
                }
                logger.debug("Authentication result for user '{}'. auth_step: '{}', result: '{}', credentials: '{}'", userId, this.authStep, result, System.identityHashCode(credentials));
            }
        }
        int overridenNextStep = -1;
        logger.trace("#########################################################################");
        logger.trace("++++++++++++++++++++++++++++++++++++++++++CURRENT ACR:" + this.authAcr);
        logger.trace("++++++++++++++++++++++++++++++++++++++++++CURRENT STEP:" + this.authStep);
        int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
        if (apiVersion > 1) {
            logger.trace("According to API version script supports steps overriding");
            overridenNextStep = externalAuthenticationService.getNextStep(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
            logger.debug("Get next step from script: '{}'", overridenNextStep);
        }
        if (!result && (overridenNextStep == -1)) {
            // Force session lastUsedAt update if authentication attempt is failed
            sessionIdService.updateSessionId(sessionId);
            return Constants.RESULT_AUTHENTICATION_FAILED;
        }
        boolean overrideCurrentStep = false;
        if (overridenNextStep > -1) {
            overrideCurrentStep = true;
            // Reload session id
            /*
 * TODO: Remove after 6.0. Check if this will not led to external script problems.
				sessionId = sessionIdService.getSessionId();
*/
            // Reset to specified step
            sessionId = sessionIdService.resetToStep(sessionId, overridenNextStep);
            if (sessionId == null) {
                return Constants.RESULT_AUTHENTICATION_FAILED;
            }
            this.authStep = overridenNextStep;
            logger.info("Authentication reset to step : '{}'", this.authStep);
        }
        // Update parameters map to allow access it from count
        // authentication steps method
        updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
        // Determine count authentication methods
        int countAuthenticationSteps = externalAuthenticationService.executeExternalGetCountAuthenticationSteps(customScriptConfiguration);
        /*
 * TODO: Remove after 6.0. Check if this will not led to external script problems.
			// Reload from LDAP to make sure that we are updating latest session
			// attributes
			sessionId = sessionIdService.getSessionId();
*/
        sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
        // Prepare for next step
        if ((this.authStep < countAuthenticationSteps) || overrideCurrentStep) {
            int nextStep;
            if (overrideCurrentStep) {
                nextStep = overridenNextStep;
            } else {
                nextStep = this.authStep + 1;
            }
            String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, nextStep);
            if (redirectTo == null) {
                return Constants.RESULT_FAILURE;
            } else if (StringHelper.isEmpty(redirectTo)) {
                redirectTo = "/login.xhtml";
            }
            // Store/Update extra parameters in session attributes map
            updateExtraParameters(customScriptConfiguration, nextStep, sessionIdAttributes);
            if (!overrideCurrentStep) {
                // Update auth_step
                sessionIdAttributes.put("auth_step", Integer.toString(nextStep));
                // Mark step as passed
                markAuthStepAsPassed(sessionIdAttributes, this.authStep);
            }
            if (sessionId != null) {
                boolean updateResult = updateSession(sessionId, sessionIdAttributes);
                if (!updateResult) {
                    return Constants.RESULT_EXPIRED;
                }
            }
            logger.trace("Redirect to page: '{}'", redirectTo);
            facesService.redirectWithExternal(redirectTo, null);
            return Constants.RESULT_SUCCESS;
        }
        if (this.authStep == countAuthenticationSteps) {
            // Store/Update extra parameters in session attributes map
            updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
            SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
            authenticationService.quietLogin(credentials.getUsername());
            // Redirect to authorization workflow
            logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
            authenticationService.onSuccessfulLogin(eventSessionId);
            logger.info("Authentication success for User: '{}'", credentials.getUsername());
            return Constants.RESULT_SUCCESS;
        }
    } else {
        if (StringHelper.isNotEmpty(credentials.getUsername())) {
            boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword());
            if (authenticated) {
                SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
                // Redirect to authorization workflow
                logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
                authenticationService.onSuccessfulLogin(eventSessionId);
            } else {
                // Force session lastUsedAt update if authentication attempt is failed
                sessionIdService.updateSessionId(sessionId);
            }
            logger.info("Authentication success for User: '{}'", credentials.getUsername());
            return Constants.RESULT_SUCCESS;
        }
    }
    return Constants.RESULT_FAILURE;
}
Also used : User(org.gluu.oxauth.model.common.User) SessionId(org.gluu.oxauth.model.common.SessionId) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration)

Example 33 with SessionId

use of org.gluu.oxauth.model.common.SessionId in project oxAuth by GluuFederation.

the class SelectAccountAction method select.

public void select() {
    try {
        log.debug("Selected account: " + selectedSessionId);
        clearSessionIdCookie();
        SessionId selectedSession = currentSessions.stream().filter(s -> s.getId().equals(selectedSessionId)).findAny().get();
        cookieService.createSessionIdCookie(selectedSession, false);
        identity.setSessionId(selectedSession);
        authenticator.authenticateBySessionId(selectedSessionId);
        String uri = buildAuthorizationUrl();
        log.trace("RedirectTo: {}", uri);
        facesService.redirectToExternalURL(uri);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) SessionId(org.gluu.oxauth.model.common.SessionId)

Example 34 with SessionId

use of org.gluu.oxauth.model.common.SessionId in project oxAuth by GluuFederation.

the class RevokeSessionRestWebService method requestRevokeSession.

@POST
@Path("/revoke_session")
@Produces({ MediaType.APPLICATION_JSON })
public Response requestRevokeSession(@FormParam("user_criterion_key") String userCriterionKey, @FormParam("user_criterion_value") String userCriterionValue, @Context HttpServletRequest request, @Context HttpServletResponse response, @Context SecurityContext sec) {
    try {
        log.debug("Attempting to revoke session: userCriterionKey = {}, userCriterionValue = {}, isSecure = {}", userCriterionKey, userCriterionValue, sec.isSecure());
        validateAccess();
        final User user = userService.getUserByAttribute(userCriterionKey, userCriterionValue);
        if (user == null) {
            log.trace("Unable to find user by {}={}", userCriterionKey, userCriterionValue);
            // no error because we don't want to disclose internal AS info about users
            return Response.ok().build();
        }
        List<SessionId> sessionIdList = sessionIdService.findByUser(user.getDn());
        if (sessionIdList == null || sessionIdList.isEmpty()) {
            log.trace("No sessions found for user uid: {}, dn: {}", user.getUserId(), user.getDn());
            return Response.ok().build();
        }
        final List<SessionId> authenticatedSessions = sessionIdList.stream().filter(sessionId -> sessionId.getState() == SessionIdState.AUTHENTICATED).collect(Collectors.toList());
        sessionIdService.remove(authenticatedSessions);
        log.debug("Revoked {} user's sessions (user: {})", authenticatedSessions.size(), user.getUserId());
        return Response.ok().build();
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(500).build();
    }
}
Also used : UserService(org.gluu.oxauth.service.UserService) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) SessionClient(org.gluu.oxauth.model.session.SessionClient) Identity(org.gluu.oxauth.security.Identity) HttpServletResponse(javax.servlet.http.HttpServletResponse) SecurityContext(javax.ws.rs.core.SecurityContext) Collectors(java.util.stream.Collectors) ScopeService(org.gluu.oxauth.service.ScopeService) SessionId(org.gluu.oxauth.model.common.SessionId) SessionIdState(org.gluu.oxauth.model.common.SessionIdState) Constants(org.gluu.oxauth.model.config.Constants) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) SessionIdService(org.gluu.oxauth.service.SessionIdService) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) User(org.gluu.oxauth.model.common.User) ErrorResponseFactory(org.gluu.oxauth.model.error.ErrorResponseFactory) EndSessionErrorResponseType(org.gluu.oxauth.model.session.EndSessionErrorResponseType) ArrayUtils(org.apache.commons.lang.ArrayUtils) User(org.gluu.oxauth.model.common.User) SessionId(org.gluu.oxauth.model.common.SessionId)

Example 35 with SessionId

use of org.gluu.oxauth.model.common.SessionId in project oxAuth by GluuFederation.

the class AuthenticationService method getAuthenticatedUser.

public User getAuthenticatedUser() {
    if (identity.getUser() != null) {
        return identity.getUser();
    } else {
        SessionId sessionId = sessionIdService.getSessionId();
        if (sessionId != null) {
            Map<String, String> sessionIdAttributes = sessionId.getSessionAttributes();
            String userId = sessionIdAttributes.get(Constants.AUTHENTICATED_USER);
            if (StringHelper.isNotEmpty(userId)) {
                User user = userService.getUser(userId);
                identity.setUser(user);
                return user;
            }
        }
    }
    return null;
}
Also used : SimpleUser(org.gluu.oxauth.model.common.SimpleUser) User(org.gluu.oxauth.model.common.User) SessionId(org.gluu.oxauth.model.common.SessionId)

Aggregations

SessionId (org.gluu.oxauth.model.common.SessionId)52 CustomScriptConfiguration (org.gluu.model.custom.script.conf.CustomScriptConfiguration)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 User (org.gluu.oxauth.model.common.User)7 Date (java.util.Date)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 URISyntaxException (java.net.URISyntaxException)4 HashMap (java.util.HashMap)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 AuthorizationGrant (org.gluu.oxauth.model.common.AuthorizationGrant)4 EntryPersistenceException (org.gluu.persist.exception.EntryPersistenceException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 BaseComponentTest (org.gluu.oxauth.BaseComponentTest)3 SimpleUser (org.gluu.oxauth.model.common.SimpleUser)3 AcrChangedException (org.gluu.oxauth.model.exception.AcrChangedException)3 InvalidSessionStateException (org.gluu.oxauth.model.exception.InvalidSessionStateException)3 Client (org.gluu.oxauth.model.registration.Client)3 ConsentGatheringContext (org.gluu.oxauth.service.external.context.ConsentGatheringContext)3 UmaGatherContext (org.gluu.oxauth.uma.authorization.UmaGatherContext)3 Parameters (org.testng.annotations.Parameters)3