Java Code Examples for org.opensaml.profile.context.ProfileRequestContext

The following examples show how to use org.opensaml.profile.context.ProfileRequestContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    final RelyingPartyContext rpCtx = profileRequestContext.getSubcontext(RelyingPartyContext.class, false);
    if (rpCtx == null) {
        throw new OIDCException("Relying party context not found in the profile request");
    }
    if (rpCtx.getRelyingPartyId() == null) {
        throw new OIDCException("Relying  party id is blank");
    }
    final SAMLMetadataContext mdCtx = new SAMLMetadataContext();

    log.debug("Created client entity descriptor for {}", rpCtx.getRelyingPartyId());
    final EntityDescriptor clientEntityDescriptor = new ClientEntityDescriptor(rpCtx.getRelyingPartyId());
    mdCtx.setEntityDescriptor(clientEntityDescriptor);
    rpCtx.setRelyingPartyIdContextTree(mdCtx);

    return Events.Success.event(this);

}
 
Example 2
@Nullable
@Override
public T apply(@Nullable final ProfileRequestContext profileRequestContext) {
    if (profileRequestContext == null) {
        log.error("Profile request context is null");
        return null;
    }

    final RelyingPartyContext rpContext = profileRequestContext.getSubcontext(RelyingPartyContext.class, false);
    if (rpContext == null) {
        log.error("There is no relying party context defined");
        return null;
    }

    log.debug("Located relying party context with id {}", rpContext.getRelyingPartyId());

    if (!this.configClass.isInstance(rpContext.getProfileConfig())) {
        log.error("{} cannot be applied or is not an instance of the relying party context profile configuration",
                this.configClass);
        return null;
    }
    return this.configClass.cast(rpContext.getProfileConfig());
}
 
Example 3
/**
 * Store spring security authentication context.
 *
 * @param profileRequestContext the profile request context
 * @param springRequestContext  the spring request context
 * @param authentication        the authentication
 */
private void storeSpringSecurityAuthenticationContext(@Nonnull final ProfileRequestContext profileRequestContext,
                                                      final RequestContext springRequestContext,
                                                      final Authentication authentication) {
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    final HttpSession session = request.getSession();
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
    log.debug("Stored authentication [{}] into Spring security context",
        SecurityContextHolder.getContext().getAuthentication());
}
 
Example 4
Source Project: shibboleth-oidc   Source File: InitializeLoginAction.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Initializing login action", getLogPrefix());
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final HttpServletResponse response = OIDCUtils.getHttpServletResponse(springRequestContext);
    if (response == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }
    HttpServletRequestResponseContext.loadCurrent(request, response);
    return Events.Success.event(this);
}
 
Example 5
@Override
public String getParameterString(final HttpServletRequest request, final String authenticationKey) {
    try {
        final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
        final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
        if (authnContext == null) {
            logger.debug("No authentication context is available");
            return "";
        }
        final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
        if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
            logger.debug("No authentication method parameter is found in the request attributes");
            return "";
        }
        final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
        final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
        if (attribute == null) {
            return "";
        }
        final String casMethod = getCasAuthenticationMethodFor(REFEDS);
        if (casMethod != null && !casMethod.isEmpty()) {
            return "&authn_method=" + casMethod;
        }
        return "";
    }catch (final Exception e) {
        logger.error(e.getMessage(), e);
        return "";
    }
}
 
Example 6
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Building authentication context", getLogPrefix());
    final AuthenticationContext ac = new AuthenticationContext();
    
    final OIDCAuthorizationRequestContext authZContext =
            profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authorizationRequest = authZContext.getAuthorizationRequest();
    if (authorizationRequest == null || Strings.isNullOrEmpty(authorizationRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    ac.setForceAuthn(authZContext.isForceAuthentication());
    if (ac.isForceAuthn()) {
        log.debug("Authentication context requires force authN for {}",
                authorizationRequest.getClientId());
    } else {
        log.debug("Authentication context does not require force authN for {}",
                authorizationRequest.getClientId());
    }

    final List<Principal> principals = new ArrayList<>();
    processRequestedAcrValuesIfAny(authorizationRequest, principals);
    processAcrValuesBasedOnPrincipalWeightMap(principals);
    addRequestedPrincipalIntoContext(ac, principals);
    
    profileRequestContext.addSubcontext(ac, true);
    profileRequestContext.setBrowserProfile(true);
    return Events.Success.event(this);
}
 
Example 7
/**
 * Gets session bound to the idp.
 *
 * @param prc the prc
 * @return the idp session
 */
@Nonnull
protected IdPSession getIdPSession(final ProfileRequestContext prc) {
    final SessionContext sessionContext = sessionContextFunction.apply(prc);
    if (sessionContext != null && sessionContext.getIdPSession() != null) {
        return sessionContext.getIdPSession();
    }
    throw new IllegalStateException("Session not found");
}
 
Example 8
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {

    final OIDCAuthorizationRequestContext authZContext = 
            profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authRequest = authZContext.getAuthorizationRequest();
    if (authRequest == null || Strings.isNullOrEmpty(authRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    final ClientDetailsEntity client = this.clientService.loadClientByClientId(authRequest.getClientId());

    if (client == null) {
        log.warn("Client configuration could not be loaded from session");
        return Events.Failure.event(this);
    }
    final RelyingPartyContext rpc = new RelyingPartyContext();

    rpc.setVerified(true);
    rpc.setRelyingPartyId(client.getClientId());
    log.debug("{} Setting up RP context for verified relying party {}",
            getLogPrefix(), client.getClientId());
    profileRequestContext.addSubcontext(rpc);
    return Events.Success.event(this);
}
 
Example 9
private static Object getAuthenticationTokenCredentials(final ProfileRequestContext profileRequestContext) {
    final AuthenticationContext ctx = profileRequestContext.getSubcontext(AuthenticationContext.class);
    if (ctx != null && ctx.containsSubcontext(UsernamePasswordContext.class)) {
        final UsernamePasswordContext subcontext = ctx.getSubcontext(UsernamePasswordContext.class);
        return subcontext.getUsername();
    }
    final SubjectContext sub = profileRequestContext.getSubcontext(SubjectContext.class);
    if (sub == null) {
        throw new OIDCException("Could not locate SubjectContext in the ProfileRequestContext");
    }
    return sub.getPrincipalName();
}
 
Example 10
/**
 * Gets authentication date time.
 *
 * @return the authentication date time
 */
private static DateTime getAuthenticationDateTime(final ProfileRequestContext profileRequestContext) {
    final AuthenticationContext ctx = profileRequestContext.getSubcontext(AuthenticationContext.class);
    if (ctx != null && ctx.getAuthenticationResult() != null) {
        return new DateTime(ctx.getAuthenticationResult().getAuthenticationInstant());
    }
    final SessionContext ctxSession = profileRequestContext.getSubcontext(SessionContext.class);
    if (ctxSession != null && ctxSession.getIdPSession() != null) {
        return new DateTime(ctxSession.getIdPSession().getCreationInstant());
    }
    throw new OIDCException("Could not determine authentication time based on authentication or session context");
}
 
Example 11
@Override
public String getParameterString(final HttpServletRequest request, final String authenticationKey) {
    try {
        final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
        final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
        if (authnContext == null) {
            logger.debug("No authentication context is available");
            return "";
        }
        final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
        if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
            logger.debug("No authentication method parameter is found in the request attributes");
            return "";
        }
        final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
        final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
        if (attribute == null) {
            return "";
        }
        final String casMethod = getCasAuthenticationMethodFor(REFEDS);
        if (casMethod != null && !casMethod.isEmpty()) {
            return "&authn_method=" + casMethod;
        }
        return "";
    }catch (final Exception e) {
        logger.error(e.getMessage(), e);
        return "";
    }
}
 
Example 12
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion, final String authenticationKey) throws Exception {

    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        logger.debug("No authentication context is available");
        return;
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
        logger.debug("No requested principal context is available in the authentication context; Overriding class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
    final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
    if (attribute == null) {
        logger.debug("No authn context class ref principal is found in the requested principals; overriding to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }
    final String authnMethod = attribute.getName();
    logger.debug("Requested authn method provided by IdP is {}", authnMethod);
    if (!assertion.getPrincipal().getAttributes().containsKey("authnContextClass")) {
        logger.debug("No authentication context class is provided by CAS; Overriding context class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Object clazz = assertion.getPrincipal().getAttributes().get("authnContextClass");
    logger.debug("Located asserted authentication context class [{}]", clazz);

    if (clazz.equals("mfa-duo")) {
        overrideAuthnContextClass(REFEDS, request, authenticationKey);
        logger.info("Validation payload successfully asserts the authentication context class for mfa-duo; Context class is set to {}", REFEDS);
        return;
    }
    logger.debug("Authentication context class [{}] provided by CAS is not one by Duo Security. "
        + "The requested authentication method to be used shall be {} and is left unmodified", clazz, authnMethod);
    overrideAuthnContextClass(clazz.toString(), request, authenticationKey);
}
 
Example 13
private void overrideAuthnContextClass(final String clazz, final HttpServletRequest request, final String authenticationKey) throws Exception {
    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        throw new IllegalArgumentException("No authentication method parameter is found in the request attributes");
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    logger.info("Overriding the principal authn context class ref to {}", clazz);
    if (principalCtx != null) {
        final List<Principal> principals = new ArrayList<>();
        final Principal principal = new AuthnContextClassRefPrincipal(clazz);
        principals.add(principal);
        principalCtx.setRequestedPrincipals(principals);
        principalCtx.setOperator("exact");
        principalCtx.setMatchingPrincipal(principal);

        principalCtx.getPrincipalEvalPredicateFactoryRegistry().register(AuthnContextClassRefPrincipal.class, "exact", new PrincipalEvalPredicateFactory() {
            @Nonnull
            @Override
            public PrincipalEvalPredicate getPredicate(@Nonnull final Principal candidate) {
                return new PrincipalEvalPredicate() {

                    @Override
                    public Principal getMatchingPrincipal() {
                        return principal;
                    }

                    @Override
                    public boolean apply(@Nullable final PrincipalSupportingComponent input) {
                        final Set supported = input != null
                            ? input.getSupportedPrincipals(principal.getClass())
                            : new HashSet();
                        return supported.stream().anyMatch(p -> principal.equals(p));
                    }
                };
            }
        });

        logger.info("The final requested authn context class ref principals are {}", principals);
    } else {
        logger.error("No requested principal context class is available");
    }
}
 
Example 14
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final HttpServletResponse response = OIDCUtils.getHttpServletResponse(springRequestContext);
    if (response == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final AuthorizationRequest authorizationRequest = createAuthorizationRequest(request);
    if (Strings.isNullOrEmpty(authorizationRequest.getClientId())) {
        throw new OIDCException("No client id is specified in the authorization request");
    }


    final OIDCAuthorizationRequestContext authZContext = new OIDCAuthorizationRequestContext();
    authZContext.setAuthorizationRequest(authorizationRequest);

    if (authZContext.isImplicitResponseType() && Strings.isNullOrEmpty(authZContext.getNonce())) {
        log.error("nonce is required since the requesting flow is implicit");
        throw new OIDCException("nonce is required when handling implicit response type");
    }
    
    final ClientDetailsEntity client = loadClientObject(authZContext);
    ensureRedirectUriIsAuthorized(authorizationRequest, client);
    
    log.debug("Found client {}.", client.getClientId());
    
    processLoginHintParameterIfNeeded(request, authZContext);

    Pair<Events, ? extends Object> pairEvent = new Pair<>(Events.Success, null);
    final String prompt = (String) authorizationRequest.getExtensions().get(ConnectRequestParameters.PROMPT);
    if (prompt != null) {
        log.debug("Authorization request contains prompt {}", prompt);
        pairEvent = checkForPrompts(prompt, request, client, authZContext);
    }

    return produceFinalEvent(profileRequestContext, response, authZContext, 
            pairEvent, springRequestContext, client);
}
 
Example 15
/**
 * Produce final event event.
 *
 * @param profileRequestContext the profile request context
 * @param response              the response
 * @param authorizationRequest  the authorization request
 * @param pairEvent             the pair event
 * @param springRequestContext  the spring request context
 * @param client   the client details entity
 * @return the event
 */
private Event produceFinalEvent(final ProfileRequestContext profileRequestContext,
                                final HttpServletResponse response,
                                final OIDCAuthorizationRequestContext authorizationRequest,
                                final Pair<Events, ? extends Object> pairEvent,
                                final RequestContext springRequestContext, 
                                final ClientDetailsEntity client) {

    try {
        if (pairEvent.getFirst() == null) {
            log.error("Could not determine the final event based on authorization request");
            return Events.BadRequest.event(this);
        }

        switch (pairEvent.getFirst()) {
            case Failure:
                log.error("Failed to process authorization request. Sending back response error");
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                break;
            case Redirect:
                if (pairEvent.getSecond() != null) {
                    log.debug("Authorization request indicated a redirect event to {}", pairEvent.getSecond());
                    final OIDCResponse oidcResponse = new OIDCResponse();
                    oidcResponse.setAuthorizationRequest(authorizationRequest.getAuthorizationRequest());
                    oidcResponse.setRedirectUri(pairEvent.getSecond().toString());
                    oidcResponse.setClient(client);
                    OIDCUtils.putOIDCResponseIntoScope(oidcResponse, springRequestContext.getFlowScope());
                } else {
                    throw new OIDCException("No redirect url could be found based on the request");
                }
                break;
            case Success:
                log.debug("Success. Proceeding with building the authorization context based on the request");
                profileRequestContext.addSubcontext(authorizationRequest, true);
                break;
            default:
                log.debug("Proceeding to final event");
        }
        final Event ev = pairEvent.getFirst().event(this);
        log.debug("Returning final event {}", ev.getId());
        return ev;
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        throw new OIDCException(e);
    }
}
 
Example 16
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {

    final OIDCAuthorizationRequestContext authZContext =
        profileRequestContext.getSubcontext(OIDCAuthorizationRequestContext.class);
    if (authZContext == null) {
        log.warn("No authorization request could be located in the profile request context");
        return Events.Failure.event(this);
    }

    final AuthorizationRequest authRequest = authZContext.getAuthorizationRequest();
    if (authRequest == null || Strings.isNullOrEmpty(authRequest.getClientId())) {
        log.warn("Authorization request could not be loaded from session");
        return Events.Failure.event(this);
    }

    /*
    final String prompt = (String)authRequest.getExtensions().get(ConnectRequestParameters.PROMPT);
    final List<String> prompts = Splitter.on(ConnectRequestParameters.PROMPT_SEPARATOR)
            .splitToList(Strings.nullToEmpty(prompt));
    */

    final ClientDetailsEntity client;

    try {
        client = clientService.loadClientByClientId(authRequest.getClientId());
        if (client == null) {
            log.error("Could not find client {}", authRequest.getClientId());
            return Events.ClientNotFound.event(this);
        }
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        return Events.BadRequest.event(this);
    }

    /*
    if (prompts.contains(ConnectRequestParameters.PROMPT_NONE)) {
        log.debug("Handling authorization when prompt contains none");
        return handleWhenNoPromptIsPresent(springRequestContext, request, authRequest, client);
    }
    */

    final Authentication authentication =
        SpringSecurityAuthenticationTokenFactory.buildAuthentication(profileRequestContext, client);
    storeSpringSecurityAuthenticationContext(profileRequestContext, springRequestContext, authentication);
    storeAuthenticationTimeIntoAuthorizationRequest(authentication, authRequest);
    final OIDCResponse response = buildOpenIdConnectResponse(authRequest, client);
    final OIDCAuthorizationResponseContext responseContext = new OIDCAuthorizationResponseContext();
    responseContext.setOidcResponse(response);
    profileRequestContext.addSubcontext(responseContext);
    return Events.Proceed.event(this);
}
 
Example 17
private static Object getAuthenticationTokenPrincipal(final ProfileRequestContext profileRequestContext) {
    return profileRequestContext.getSubcontext(SubjectContext.class);
}
 
Example 18
@Override
public boolean apply(@Nullable final ProfileRequestContext input) {
    final RelyingPartyContext rpc = getRelyingPartyContextLookupStrategy().apply(input);
    return rpc != null;
}
 
Example 19
Source Project: oxTrust   Source File: AuthenticationFilter.java    License: MIT License 4 votes vote down vote up
public String getOAuthRedirectUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String authorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String clientScopes = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, null);

    String clientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String clientSecret = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (clientSecret != null) {
        try {
            clientSecret = StringEncrypter.defaultInstance().decrypt(clientSecret, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }

    String redirectUri = constructRedirectUrl(request);

    List<String> scopes = Arrays.asList(clientScopes.split(StringUtils.SPACE));
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    // Lookup for relying party ID
    final String key = request.getParameter(ExternalAuthentication.CONVERSATION_KEY);
    request.getSession().setAttribute(SESSION_CONVERSATION_KEY, key);
    ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, request);

    String relyingPartyId = "";
    final RelyingPartyContext relyingPartyCtx = prc.getSubcontext(RelyingPartyContext.class);
    if (relyingPartyCtx != null) {
        relyingPartyId = relyingPartyCtx.getRelyingPartyId();
        log.info("relyingPartyId found: " + relyingPartyId);
    } else
        log.warn("No RelyingPartyContext was available");

    // JWT
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    JwtState jwtState = new JwtState(SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    if (relyingPartyId != null && !"".equals(relyingPartyId)) {
        String additionalClaims = String.format("{relyingPartyId: '%s'}", relyingPartyId);
        jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    } else
        log.warn("No relyingPartyId was available");
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    Cookie currentShibstateCookie = getCurrentShibstateCookie(request);
    if (currentShibstateCookie != null) {
        String requestUri = decodeCookieValue(currentShibstateCookie.getValue());
        log.debug("requestUri = \"" + requestUri + "\"");

        String authenticationMode = determineAuthenticationMode(requestUri);

        if (StringHelper.isNotEmpty(authenticationMode)) {
            log.debug("acr_values = \"" + authenticationMode + "\"");
            authorizationRequest.setAcrValues(Arrays.asList(authenticationMode));
            updateShibstateCookie(response, currentShibstateCookie, requestUri, "/" + Configuration.OXAUTH_ACR_VALUES + "/" + authenticationMode);
        }
    }

    // Store for validation in session
    final HttpSession session = request.getSession(false);
    session.setAttribute(Configuration.SESSION_AUTH_STATE, encodedState);
    session.setAttribute(Configuration.SESSION_AUTH_NONCE, nonce);

    return authorizeUrl + "?" + authorizationRequest.getQueryString();
}
 
Example 20
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response, final Assertion assertion, final String authenticationKey) throws Exception {

    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        logger.debug("No authentication context is available");
        return;
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    if (principalCtx == null || principalCtx.getRequestedPrincipals().isEmpty()) {
        logger.debug("No requested principal context is available in the authentication context; Overriding class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Principal principal = new AuthnContextClassRefPrincipal(REFEDS);
    final Principal attribute = principalCtx.getRequestedPrincipals().stream().filter(p -> p.equals(principal)).findFirst().orElse(null);
    if (attribute == null) {
        logger.debug("No authn context class ref principal is found in the requested principals; overriding to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }
    final String authnMethod = attribute.getName();
    logger.debug("Requested authn method provided by IdP is {}", authnMethod);
    if (!assertion.getPrincipal().getAttributes().containsKey("authnContextClass")) {
        logger.debug("No authentication context class is provided by CAS; Overriding context class to {}", AuthnContext.PPT_AUTHN_CTX);
        overrideAuthnContextClass(AuthnContext.PPT_AUTHN_CTX, request, authenticationKey);
        return;
    }

    final Object clazz = assertion.getPrincipal().getAttributes().get("authnContextClass");
    logger.debug("Located asserted authentication context class [{}]", clazz);

    if (clazz.equals("mfa-duo")) {
        overrideAuthnContextClass(REFEDS, request, authenticationKey);
        logger.info("Validation payload successfully asserts the authentication context class for mfa-duo; Context class is set to {}", REFEDS);
        return;
    }
    logger.debug("Authentication context class [{}] provided by CAS is not one by Duo Security. "
        + "The requested authentication method to be used shall be {} and is left unmodified", clazz, authnMethod);
    overrideAuthnContextClass(clazz.toString(), request, authenticationKey);
}
 
Example 21
private void overrideAuthnContextClass(final String clazz, final HttpServletRequest request, final String authenticationKey) throws Exception {
    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(authenticationKey, request);
    final AuthenticationContext authnContext = prc.getSubcontext(AuthenticationContext.class, true);
    if (authnContext == null) {
        throw new IllegalArgumentException("No authentication method parameter is found in the request attributes");
    }
    final RequestedPrincipalContext principalCtx = authnContext.getSubcontext(RequestedPrincipalContext.class, true);
    logger.info("Overriding the principal authn context class ref to {}", clazz);
    if (principalCtx != null) {
        final List<Principal> principals = new ArrayList<>();
        final Principal principal = new AuthnContextClassRefPrincipal(clazz);
        principals.add(principal);
        principalCtx.setRequestedPrincipals(principals);
        principalCtx.setOperator("exact");
        principalCtx.setMatchingPrincipal(principal);

        principalCtx.getPrincipalEvalPredicateFactoryRegistry().register(AuthnContextClassRefPrincipal.class, "exact", new PrincipalEvalPredicateFactory() {
            @Nonnull
            @Override
            public PrincipalEvalPredicate getPredicate(@Nonnull final Principal candidate) {
                return new PrincipalEvalPredicate() {

                    @Override
                    public Principal getMatchingPrincipal() {
                        return principal;
                    }

                    @Override
                    public boolean apply(@Nullable final PrincipalSupportingComponent input) {
                        final Set supported = input != null
                            ? input.getSupportedPrincipals(principal.getClass())
                            : new HashSet();
                        return supported.stream().anyMatch(p -> principal.equals(p));
                    }
                };
            }
        });

        logger.info("The final requested authn context class ref principals are {}", principals);
    } else {
        logger.error("No requested principal context class is available");
    }
}