Search in sources :

Example 1 with SessionId

use of io.jans.as.server.model.common.SessionId in project jans by JanssenProject.

the class ConsentGathererService method configure.

public boolean configure(String userDn, String clientId, String state) {
    final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
    final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
    final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, userDn, true);
    CustomScriptConfiguration script = determineConsentScript(clientId);
    if (script == null) {
        log.error("Failed to determine consent-gathering script");
        return false;
    }
    sessionService.configure(session, script.getName(), clientId, state);
    this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
    log.debug("Configuring consent-gathering script '{}'", script.getName());
    int step = sessionService.getStep(session);
    String redirectTo = external.getPageForStep(script, step, context);
    if (StringHelper.isEmpty(redirectTo)) {
        log.error("Failed to determine page for consent-gathering script");
        return false;
    }
    context.persist();
    log.trace("Redirecting to page: '{}'", redirectTo);
    facesService.redirectWithExternal(redirectTo, null);
    return true;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ConsentGatheringContext(io.jans.as.server.service.external.context.ConsentGatheringContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 2 with SessionId

use of io.jans.as.server.model.common.SessionId in project jans by JanssenProject.

the class ConsentGathererService method prepareForStep.

public String prepareForStep() {
    try {
        final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
        final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
        final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, null, false);
        if (session == null || session.getSessionAttributes().isEmpty()) {
            log.error("Failed to restore claim-gathering session state");
            return result(Constants.RESULT_EXPIRED);
        }
        CustomScriptConfiguration script = getScript(session);
        if (script == null) {
            log.error("Failed to find script '{}' in session:", sessionService.getScriptName(session));
            return result(Constants.RESULT_FAILURE);
        }
        int step = sessionService.getStep(session);
        if (step < 1) {
            log.error("Invalid step: {}", step);
            return result(Constants.RESULT_INVALID_STEP);
        }
        if (!sessionService.isPassedPreviousSteps(session, step)) {
            log.error("There are consent-gathering steps not marked as passed. scriptName: '{}', step: '{}'", script.getName(), step);
            return result(Constants.RESULT_FAILURE);
        }
        this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
        boolean result = external.prepareForStep(script, step, context);
        log.debug("Consent-gathering prepare for step result for script '{}', step: '{}', gatheredResult: '{}'", script.getName(), step, result);
        if (result) {
            context.persist();
            return result(Constants.RESULT_SUCCESS);
        }
    } catch (Exception ex) {
        log.error("Failed to prepareForStep()", ex);
    }
    return result(Constants.RESULT_FAILURE);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ConsentGatheringContext(io.jans.as.server.service.external.context.ConsentGatheringContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionId(io.jans.as.server.model.common.SessionId) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 3 with SessionId

use of io.jans.as.server.model.common.SessionId in project jans by JanssenProject.

the class DeviceAuthorizationAction method processUserCodeVerification.

/**
 * Processes user code introduced or loaded in the veritification page and redirects whether user code is correct
 * or return an error if there is something wrong.
 */
public void processUserCodeVerification() {
    SessionId session = sessionIdService.getSessionId();
    if (session == null) {
        facesMessages.add(FacesMessage.SEVERITY_WARN, languageBean.getMessage("error.errorEncountered"));
        return;
    }
    if (!preventBruteForcing(session)) {
        facesMessages.add(FacesMessage.SEVERITY_WARN, languageBean.getMessage("device.authorization.brute.forcing.msg"));
        return;
    }
    String userCode;
    if (StringUtils.isBlank(userCodePart1) && StringUtils.isBlank(userCodePart2)) {
        userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
    } else {
        userCode = userCodePart1 + '-' + userCodePart2;
    }
    userCode = userCode.toUpperCase();
    if (!validateFormat(userCode)) {
        facesMessages.add(FacesMessage.SEVERITY_WARN, languageBean.getMessage("device.authorization.invalid.user.code"));
        return;
    }
    DeviceAuthorizationCacheControl cacheData = deviceAuthorizationService.getDeviceAuthzByUserCode(userCode);
    log.debug("Verifying device authorization cache data: {}", cacheData);
    String message = null;
    if (cacheData != null) {
        if (cacheData.getStatus() == DeviceAuthorizationStatus.PENDING) {
            session.getSessionAttributes().put(SESSION_USER_CODE, userCode);
            session.getSessionAttributes().remove(SESSION_LAST_ATTEMPT);
            session.getSessionAttributes().remove(SESSION_ATTEMPTS);
            sessionIdService.updateSessionId(session);
            redirectToAuthorization(cacheData);
        } else if (cacheData.getStatus() == DeviceAuthorizationStatus.DENIED) {
            message = languageBean.getMessage("device.authorization.access.denied.msg");
        } else {
            message = languageBean.getMessage("device.authorization.expired.code.msg");
        }
    } else {
        message = languageBean.getMessage("device.authorization.invalid.user.code");
    }
    if (message != null) {
        facesMessages.add(FacesMessage.SEVERITY_WARN, message);
    }
}
Also used : DeviceAuthorizationCacheControl(io.jans.as.server.model.common.DeviceAuthorizationCacheControl) SessionId(io.jans.as.server.model.common.SessionId)

Example 4 with SessionId

use of io.jans.as.server.model.common.SessionId in project jans by JanssenProject.

the class LogoutAction method redirect.

public void redirect() {
    SessionId sessionId = sessionIdService.getSessionId();
    boolean validationResult = validateParameters();
    if (!validationResult) {
        try {
            restoreLogoutParametersFromSession(sessionId);
        } catch (IOException ex) {
            logoutFailed();
            log.debug("Failed to restore logout parameters from session", ex);
        }
        validationResult = validateParameters();
        if (!validationResult) {
            missingLogoutParameters();
            return;
        }
    }
    ExternalLogoutResult externalLogoutResult = processExternalAuthenticatorLogOut(sessionId);
    if (ExternalLogoutResult.FAILURE == externalLogoutResult) {
        logoutFailed();
        return;
    } else if (ExternalLogoutResult.REDIRECT == externalLogoutResult) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    // Required parameters
    if (idTokenHint != null && !idTokenHint.isEmpty()) {
        sb.append(EndSessionRequestParam.ID_TOKEN_HINT + "=").append(idTokenHint);
    }
    if (sessionId != null && !postLogoutRedirectUri.isEmpty()) {
        sb.append("&" + EndSessionRequestParam.SID + "=").append(sessionId.getOutsideSid());
    }
    if (postLogoutRedirectUri != null && !postLogoutRedirectUri.isEmpty()) {
        sb.append("&" + EndSessionRequestParam.POST_LOGOUT_REDIRECT_URI + "=").append(postLogoutRedirectUri);
    }
    facesService.redirectToExternalURL("restv1/end_session?" + sb.toString());
}
Also used : IOException(java.io.IOException) SessionId(io.jans.as.server.model.common.SessionId)

Example 5 with SessionId

use of io.jans.as.server.model.common.SessionId in project jans by JanssenProject.

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);
        boolean tokenEndpoint = requestUrl.endsWith("/token");
        boolean tokenRevocationEndpoint = requestUrl.endsWith("/revoke");
        boolean backchannelAuthenticationEnpoint = requestUrl.endsWith("/bc-authorize");
        boolean deviceAuthorizationEndpoint = requestUrl.endsWith("/device_authorization");
        boolean revokeSessionEndpoint = requestUrl.endsWith("/revoke_session");
        boolean isParEndpoint = requestUrl.endsWith("/par");
        String authorizationHeader = httpRequest.getHeader(Constants.AUTHORIZATION);
        String dpopHeader = httpRequest.getHeader("DPoP");
        if (processMTLS(httpRequest, httpResponse, filterChain)) {
            return;
        }
        if ((tokenRevocationEndpoint || deviceAuthorizationEndpoint) && clientService.isPublic(httpRequest.getParameter(Constants.CLIENT_ID))) {
            log.trace("Skipped authentication for {} for public client.", tokenRevocationEndpoint ? "Token Revocation" : "Device Authorization");
            filterChain.doFilter(httpRequest, httpResponse);
            return;
        }
        if (tokenEndpoint || revokeSessionEndpoint || tokenRevocationEndpoint || deviceAuthorizationEndpoint || isParEndpoint) {
            log.debug("Starting endpoint authentication {}", requestUrl);
            // #686 : allow authenticated client via user access_token
            final String accessToken = tokenService.getToken(authorizationHeader, HttpAuthTokenType.Bearer, HttpAuthTokenType.AccessToken);
            if (StringUtils.isNotBlank(accessToken)) {
                processAuthByAccessToken(accessToken, httpRequest, httpResponse, filterChain);
                return;
            }
            if (httpRequest.getParameter(Constants.CLIENT_ASSERTION) != null && httpRequest.getParameter(Constants.CLIENT_ASSERTION_TYPE) != null) {
                log.debug("Starting JWT token endpoint authentication");
                processJwtAuth(httpRequest, httpResponse, filterChain);
            } else if (tokenService.isBasicAuthToken(authorizationHeader)) {
                log.debug("Starting Basic Auth token endpoint authentication");
                processBasicAuth(httpRequest, httpResponse, filterChain);
            } else if (tokenEndpoint && StringUtils.isNotBlank(dpopHeader)) {
                processDPoP(httpRequest, httpResponse, filterChain);
            } else {
                log.debug("Starting POST Auth token endpoint authentication");
                processPostAuth(clientFilterService, httpRequest, httpResponse, filterChain, tokenEndpoint);
            }
        } else if (backchannelAuthenticationEnpoint) {
            if (httpRequest.getParameter(Constants.CLIENT_ASSERTION) != null && httpRequest.getParameter(Constants.CLIENT_ASSERTION_TYPE) != null) {
                log.debug("Starting JWT token endpoint authentication");
                processJwtAuth(httpRequest, httpResponse, filterChain);
            } else if (tokenService.isBasicAuthToken(authorizationHeader)) {
                processBasicAuth(httpRequest, httpResponse, filterChain);
            } else {
                String entity = errorResponseFactory.getErrorAsJson(INVALID_REQUEST);
                httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
                httpResponse.addHeader(Constants.WWW_AUTHENTICATE, getRealmHeaderValue());
                httpResponse.setContentType(ContentType.APPLICATION_JSON.toString());
                httpResponse.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.length()));
                PrintWriter out = httpResponse.getWriter();
                out.print(entity);
                out.flush();
            }
        } else if (authorizationHeader != null && !tokenService.isNegotiateAuthToken(authorizationHeader)) {
            if (tokenService.isBearerAuthToken(authorizationHeader)) {
                processBearerAuth(httpRequest, httpResponse, filterChain);
            } else if (tokenService.isBasicAuthToken(authorizationHeader)) {
                processBasicAuth(httpRequest, httpResponse, filterChain);
            } else {
                httpResponse.addHeader(Constants.WWW_AUTHENTICATE, getRealmHeaderValue());
                httpResponse.sendError(401, "Not authorized");
            }
        } else {
            String sessionId = cookieService.getSessionIdFromCookie(httpRequest);
            List<io.jans.as.model.common.Prompt> prompts = io.jans.as.model.common.Prompt.fromString(httpRequest.getParameter(AuthorizeRequestParam.PROMPT), " ");
            if (StringUtils.isBlank(sessionId) && isTrue(appConfiguration.getSessionIdRequestParameterEnabled())) {
                sessionId = httpRequest.getParameter(AuthorizeRequestParam.SESSION_ID);
            }
            SessionId sessionIdObject = null;
            if (StringUtils.isNotBlank(sessionId)) {
                sessionIdObject = sessionIdService.getSessionId(sessionId);
            }
            if (sessionIdObject != null && SessionIdState.AUTHENTICATED == sessionIdObject.getState() && !prompts.contains(io.jans.as.model.common.Prompt.LOGIN)) {
                processSessionAuth(sessionId, httpRequest, httpResponse, filterChain);
            } else {
                filterChain.doFilter(httpRequest, httpResponse);
            }
        }
    } catch (WebApplicationException ex) {
        log.trace(ex.getMessage(), ex);
        if (ex.getResponse() != null) {
            sendResponse(httpResponse, ex);
            return;
        }
        log.error(ex.getMessage(), ex);
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) WebApplicationException(javax.ws.rs.WebApplicationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionId(io.jans.as.server.model.common.SessionId) ServletException(javax.servlet.ServletException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Aggregations

SessionId (io.jans.as.server.model.common.SessionId)52 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 User (io.jans.as.common.model.common.User)9 Date (java.util.Date)9 WebApplicationException (javax.ws.rs.WebApplicationException)9 CustomScriptConfiguration (io.jans.model.custom.script.conf.CustomScriptConfiguration)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)8 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)6 Client (io.jans.as.common.model.registration.Client)4 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)4 EntryPersistenceException (io.jans.orm.exception.EntryPersistenceException)4 Path (javax.ws.rs.Path)4 SimpleUser (io.jans.as.common.model.common.SimpleUser)3 BaseComponentTest (io.jans.as.server.BaseComponentTest)3 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 LDAPException (com.unboundid.ldap.sdk.LDAPException)2 ComponentType (io.jans.as.model.common.ComponentType)2 Prompt (io.jans.as.model.common.Prompt)2 ErrorResponseFactory (io.jans.as.model.error.ErrorResponseFactory)2