Search in sources :

Example 16 with SessionState

use of org.xdi.oxauth.model.common.SessionState in project oxAuth by GluuFederation.

the class AuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    try {
        final String requestUrl = httpRequest.getRequestURL().toString();
        log.trace("Get request to: '{}'", requestUrl);
        if (requestUrl.endsWith("/token") && ServerUtil.isSameRequestPath(requestUrl, appConfiguration.getTokenEndpoint())) {
            log.debug("Starting token endpoint authentication");
            if (httpRequest.getParameter("client_assertion") != null && httpRequest.getParameter("client_assertion_type") != null) {
                log.debug("Starting JWT token endpoint authentication");
                processJwtAuth(httpRequest, httpResponse, filterChain);
            } else if (httpRequest.getHeader("Authorization") != null && httpRequest.getHeader("Authorization").startsWith("Basic ")) {
                log.debug("Starting Basic Auth token endpoint authentication");
                processBasicAuth(clientService, errorResponseFactory, httpRequest, httpResponse, filterChain);
            } else {
                log.debug("Starting POST Auth token endpoint authentication");
                processPostAuth(clientService, clientFilterService, errorResponseFactory, httpRequest, httpResponse, filterChain);
            }
        } else if (httpRequest.getHeader("Authorization") != null) {
            String header = httpRequest.getHeader("Authorization");
            if (header.startsWith("Bearer ")) {
                processBearerAuth(httpRequest, httpResponse, filterChain);
            } else if (header.startsWith("Basic ")) {
                processBasicAuth(clientService, errorResponseFactory, httpRequest, httpResponse, filterChain);
            } else {
                httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealm() + "\"");
                httpResponse.sendError(401, "Not authorized");
            }
        } else {
            String sessionState = httpRequest.getParameter(AuthorizeRequestParam.SESSION_STATE);
            List<Prompt> prompts = Prompt.fromString(httpRequest.getParameter(AuthorizeRequestParam.PROMPT), " ");
            if (StringUtils.isBlank(sessionState)) {
                // OXAUTH-297 : check whether session_state is present in
                // cookie
                sessionState = sessionStateService.getSessionStateFromCookie(httpRequest);
            }
            SessionState sessionStateObject = null;
            if (StringUtils.isNotBlank(sessionState)) {
                sessionStateObject = sessionStateService.getSessionState(sessionState);
            }
            if (sessionStateObject != null && SessionIdState.AUTHENTICATED == sessionStateObject.getState() && !prompts.contains(Prompt.LOGIN)) {
                processSessionAuth(errorResponseFactory, sessionState, httpRequest, httpResponse, filterChain);
            } else {
                filterChain.doFilter(httpRequest, httpResponse);
            }
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SessionState(org.xdi.oxauth.model.common.SessionState) HttpServletResponse(javax.servlet.http.HttpServletResponse) List(java.util.List) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 17 with SessionState

use of org.xdi.oxauth.model.common.SessionState in project oxAuth by GluuFederation.

the class Authenticator method userAuthenticationInteractive.

private boolean userAuthenticationInteractive() {
    SessionState sessionState = sessionStateService.getSessionState();
    Map<String, String> sessionIdAttributes = sessionStateService.getSessionAttributes(sessionState);
    if (sessionIdAttributes == null) {
        log.error("Failed to get session attributes");
        authenticationFailedSessionInvalid();
        return false;
    }
    // Set current state into identity to allow use in login form and
    // authentication scripts
    identity.setSessionState(sessionState);
    initCustomAuthenticatorVariables(sessionIdAttributes);
    boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
    if (useExternalAuthenticator && !StringHelper.isEmpty(this.authAcr)) {
        initCustomAuthenticatorVariables(sessionIdAttributes);
        if ((this.authStep == null) || StringHelper.isEmpty(this.authAcr)) {
            log.error("Failed to determine authentication mode");
            authenticationFailedSessionInvalid();
            return false;
        }
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
        if (customScriptConfiguration == null) {
            log.error("Failed to get CustomScriptConfiguration for acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return false;
        }
        // Check if all previous steps had passed
        boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep);
        if (!passedPreviousSteps) {
            log.error("There are authentication steps not marked as passed. acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
            return false;
        }
        boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
        log.debug("Authentication result for user '{}'. auth_step: '{}', result: '{}', credentials: '{}'", credentials.getUsername(), this.authStep, result, System.identityHashCode(credentials));
        int overridenNextStep = -1;
        int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
        if (apiVersion > 1) {
            log.trace("According to API version script supports steps overriding");
            overridenNextStep = externalAuthenticationService.getNextStep(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
            log.debug("Get next step from script: '{}'", apiVersion);
        }
        if (!result && (overridenNextStep == -1)) {
            return false;
        }
        boolean overrideCurrentStep = false;
        if (overridenNextStep > -1) {
            overrideCurrentStep = true;
            // Reload session state
            sessionState = sessionStateService.getSessionState();
            // Reset to pecified step
            sessionStateService.resetToStep(sessionState, overridenNextStep);
            this.authStep = overridenNextStep;
            log.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);
        // Reload from LDAP to make sure that we are updating latest session
        // attributes
        sessionState = sessionStateService.getSessionState();
        sessionIdAttributes = sessionStateService.getSessionAttributes(sessionState);
        // 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 (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 (sessionState != null) {
                boolean updateResult = updateSession(sessionState, sessionIdAttributes);
                if (!updateResult) {
                    return false;
                }
            }
            log.trace("Redirect to page: '{}'", redirectTo);
            facesService.redirect(redirectTo);
            return true;
        }
        if (this.authStep == countAuthenticationSteps) {
            SessionState eventSessionState = authenticationService.configureSessionUser(sessionState, sessionIdAttributes);
            Principal principal = new SimplePrincipal(credentials.getUsername());
            identity.acceptExternallyAuthenticatedPrincipal(principal);
            identity.quietLogin();
            // Redirect to authorization workflow
            log.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
            authenticationService.onSuccessfulLogin(eventSessionState);
            log.info("Authentication success for User: '{}'", credentials.getUsername());
            return true;
        }
    } else {
        if (StringHelper.isNotEmpty(credentials.getUsername())) {
            boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword());
            if (authenticated) {
                SessionState eventSessionState = authenticationService.configureSessionUser(sessionState, sessionIdAttributes);
                // Redirect to authorization workflow
                log.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
                authenticationService.onSuccessfulLogin(eventSessionState);
            }
            log.info("Authentication success for User: '{}'", credentials.getUsername());
            return true;
        }
    }
    return false;
}
Also used : SessionState(org.xdi.oxauth.model.common.SessionState) CustomScriptConfiguration(org.xdi.model.custom.script.conf.CustomScriptConfiguration) SimplePrincipal(org.xdi.model.security.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.xdi.model.security.SimplePrincipal)

Example 18 with SessionState

use of org.xdi.oxauth.model.common.SessionState in project oxAuth by GluuFederation.

the class AuthorizeAction method checkPermissionGranted.

public void checkPermissionGranted() {
    if ((clientId == null) || clientId.isEmpty()) {
        log.error("Permission denied. client_id should be not empty.");
        permissionDenied();
        return;
    }
    Client client = null;
    try {
        client = clientService.getClient(clientId);
    } catch (EntryPersistenceException ex) {
        log.error("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
        permissionDenied();
        return;
    }
    if (client == null) {
        log.error("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
        permissionDenied();
        return;
    }
    SessionState session = getSession();
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    try {
        session = sessionStateService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
    } catch (AcrChangedException e) {
        log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
        if (prompts.contains(Prompt.LOGIN)) {
            session = handleAcrChange(session, prompts);
        } else {
            log.error("Please provide prompt=login to force login with new ACR or otherwise perform logout and re-authenticate.");
            permissionDenied();
            return;
        }
    }
    if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
        Map<String, String> parameterMap = externalContext.getRequestParameterMap();
        Map<String, String> requestParameterMap = authenticationService.getAllowedParameters(parameterMap);
        String redirectTo = "/login.xhtml";
        boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
        if (useExternalAuthenticator) {
            List<String> acrValuesList = acrValuesList();
            if (acrValuesList.isEmpty()) {
                if (StringHelper.isNotEmpty(defaultAuthenticationMode.getName())) {
                    acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
                } else {
                    CustomScriptConfiguration defaultExternalAuthenticator = externalAuthenticationService.getDefaultExternalAuthenticator(AuthenticationScriptUsageType.INTERACTIVE);
                    if (defaultExternalAuthenticator != null) {
                        acrValuesList = Arrays.asList(defaultExternalAuthenticator.getName());
                    }
                }
            }
            CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
            if (customScriptConfiguration == null) {
                log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
                permissionDenied();
                return;
            }
            String acr = customScriptConfiguration.getName();
            requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
            requestParameterMap.put("auth_step", Integer.toString(1));
            String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
            if (StringHelper.isNotEmpty(tmpRedirectTo)) {
                log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
                redirectTo = tmpRedirectTo;
            }
        }
        // Store Remote IP
        String remoteIp = networkService.getRemoteIp();
        requestParameterMap.put(Constants.REMOTE_IP, remoteIp);
        // Create unauthenticated session
        SessionState unauthenticatedSession = sessionStateService.generateUnauthenticatedSessionState(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
        unauthenticatedSession.setSessionAttributes(requestParameterMap);
        unauthenticatedSession.addPermission(clientId, false);
        // always persist is prompt is not none
        boolean persisted = sessionStateService.persistSessionState(unauthenticatedSession, !prompts.contains(Prompt.NONE));
        if (persisted && log.isTraceEnabled()) {
            log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
        }
        this.sessionState = unauthenticatedSession.getId();
        sessionStateService.createSessionStateCookie(this.sessionState);
        Map<String, Object> loginParameters = new HashMap<String, Object>();
        if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
        }
        facesService.redirect(redirectTo, loginParameters);
        return;
    }
    if (StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
        permissionDenied();
    }
    final User user = userService.getUserByDn(session.getUserDn());
    log.trace("checkPermissionGranted, user = " + user);
    if (AuthorizeParamsValidator.noNonePrompt(prompts)) {
        if (appConfiguration.getTrustedClientEnabled()) {
            // if trusted client = true, then skip authorization page and grant access directly
            if (client.getTrustedClient() && !prompts.contains(Prompt.CONSENT)) {
                permissionGranted(session);
                return;
            }
        }
        if (client.getPersistClientAuthorizations()) {
            ClientAuthorizations clientAuthorizations = clientAuthorizationsService.findClientAuthorizations(user.getAttribute("inum"), client.getClientId());
            if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(org.xdi.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
                permissionGranted(session);
                return;
            }
        }
    } else {
        invalidRequest();
    }
    return;
}
Also used : SessionState(org.xdi.oxauth.model.common.SessionState) User(org.xdi.oxauth.model.common.User) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) ClientAuthorizations(org.xdi.oxauth.model.ldap.ClientAuthorizations) AcrChangedException(org.xdi.oxauth.model.exception.AcrChangedException) Prompt(org.xdi.oxauth.model.common.Prompt) Client(org.xdi.oxauth.model.registration.Client) CustomScriptConfiguration(org.xdi.model.custom.script.conf.CustomScriptConfiguration)

Example 19 with SessionState

use of org.xdi.oxauth.model.common.SessionState in project oxAuth by GluuFederation.

the class SessionStateService method generateSessionState.

private SessionState generateSessionState(String userDn, Date authenticationDate, SessionIdState state, Map<String, String> sessionIdAttributes, boolean persist) {
    final String uuid = UUID.randomUUID().toString();
    final String dn = dn(uuid);
    if (StringUtils.isBlank(dn)) {
        return null;
    }
    if (SessionIdState.AUTHENTICATED == state) {
        if (StringUtils.isBlank(userDn)) {
            return null;
        }
    }
    final SessionState sessionState = new SessionState();
    sessionState.setId(uuid);
    sessionState.setDn(dn);
    sessionState.setUserDn(userDn);
    Boolean sessionAsJwt = appConfiguration.getSessionAsJwt();
    sessionState.setIsJwt(sessionAsJwt != null && sessionAsJwt);
    if (authenticationDate != null) {
        sessionState.setAuthenticationTime(authenticationDate);
    }
    if (state != null) {
        sessionState.setState(state);
    }
    sessionState.setSessionAttributes(sessionIdAttributes);
    sessionState.setLastUsedAt(new Date());
    if (sessionState.getIsJwt()) {
        sessionState.setJwt(generateJwt(sessionState, userDn).asString());
    }
    boolean persisted = false;
    if (persist) {
        persisted = persistSessionState(sessionState);
    }
    auditLogging(sessionState);
    log.trace("Generated new session, id = '{}', state = '{}', asJwt = '{}', persisted = '{}'", sessionState.getId(), sessionState.getState(), sessionState.getIsJwt(), persisted);
    return sessionState;
}
Also used : SessionState(org.xdi.oxauth.model.common.SessionState)

Example 20 with SessionState

use of org.xdi.oxauth.model.common.SessionState in project oxAuth by GluuFederation.

the class SessionStateService method getSessionState.

public SessionState getSessionState(String sessionState) {
    if (StringHelper.isEmpty(sessionState)) {
        return null;
    }
    try {
        final SessionState entity = getSessionById(sessionState);
        log.trace("Try to get session by id: {} ...", sessionState);
        if (entity != null) {
            log.trace("Session dn: {}", entity.getDn());
            if (isSessionValid(entity)) {
                return entity;
            }
        }
    } catch (Exception ex) {
        log.trace(ex.getMessage(), ex);
    }
    log.trace("Failed to get session by id: {}", sessionState);
    return null;
}
Also used : SessionState(org.xdi.oxauth.model.common.SessionState) EmptyEntryPersistenceException(org.gluu.site.ldap.persistence.exception.EmptyEntryPersistenceException) AcrChangedException(org.xdi.oxauth.model.exception.AcrChangedException) LDAPException(com.unboundid.ldap.sdk.LDAPException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException)

Aggregations

SessionState (org.xdi.oxauth.model.common.SessionState)30 AuthorizationGrant (org.xdi.oxauth.model.common.AuthorizationGrant)5 User (org.xdi.oxauth.model.common.User)5 CustomScriptConfiguration (org.xdi.model.custom.script.conf.CustomScriptConfiguration)4 Date (java.util.Date)3 EntryPersistenceException (org.gluu.site.ldap.persistence.exception.EntryPersistenceException)3 Parameters (org.testng.annotations.Parameters)3 Test (org.testng.annotations.Test)3 BaseComponentTest (org.xdi.oxauth.BaseComponentTest)3 SimpleUser (org.xdi.oxauth.model.common.SimpleUser)3 AcrChangedException (org.xdi.oxauth.model.exception.AcrChangedException)3 Client (org.xdi.oxauth.model.registration.Client)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 OAuth2AuditLog (org.xdi.oxauth.model.audit.OAuth2AuditLog)2 Prompt (org.xdi.oxauth.model.common.Prompt)2 InvalidJwtException (org.xdi.oxauth.model.exception.InvalidJwtException)2 ClientAuthorizations (org.xdi.oxauth.model.ldap.ClientAuthorizations)2 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)1