Search in sources :

Example 1 with OkAction

use of org.pac4j.core.exception.http.OkAction in project pac4j by pac4j.

the class PostSAML2ClientTests method testRelayState.

@Test
public void testRelayState() {
    final var client = getClient();
    final WebContext context = MockWebContext.create();
    final SessionStore sessionStore = new MockSessionStore();
    sessionStore.set(context, SAML2StateGenerator.SAML_RELAY_STATE_ATTRIBUTE, "relayState");
    final var action = (OkAction) client.getRedirectionAction(context, sessionStore).get();
    assertTrue(action.getContent().contains("<input type=\"hidden\" name=\"RelayState\" value=\"relayState\"/>"));
}
Also used : MockSessionStore(org.pac4j.core.context.session.MockSessionStore) SessionStore(org.pac4j.core.context.session.SessionStore) WebContext(org.pac4j.core.context.WebContext) MockWebContext(org.pac4j.core.context.MockWebContext) MockSessionStore(org.pac4j.core.context.session.MockSessionStore) OkAction(org.pac4j.core.exception.http.OkAction) Test(org.junit.Test)

Example 2 with OkAction

use of org.pac4j.core.exception.http.OkAction in project pac4j by pac4j.

the class PostSAML2ClientTests method testForceAuthIsSetForPostBinding.

@Test
public void testForceAuthIsSetForPostBinding() {
    final var client = getClient();
    client.getConfiguration().setForceAuth(true);
    final var action = (OkAction) client.getRedirectionAction(MockWebContext.create(), new MockSessionStore()).get();
    assertTrue(getDecodedAuthnRequest(action.getContent()).contains("ForceAuthn=\"true\""));
}
Also used : MockSessionStore(org.pac4j.core.context.session.MockSessionStore) OkAction(org.pac4j.core.exception.http.OkAction) Test(org.junit.Test)

Example 3 with OkAction

use of org.pac4j.core.exception.http.OkAction in project pac4j by pac4j.

the class PostSAML2ClientTests method testCustomSpEntityIdForPostBinding.

@Test
public void testCustomSpEntityIdForPostBinding() {
    final var client = getClient();
    client.getConfiguration().setServiceProviderEntityId("http://localhost:8080/cb");
    client.getConfiguration().setUseNameQualifier(true);
    final var person = new SAML2MetadataContactPerson();
    person.setCompanyName("Pac4j");
    person.setGivenName("Bob");
    person.setSurname("Smith");
    person.setType("technical");
    person.setEmailAddresses(Collections.singletonList("test@example.org"));
    person.setTelephoneNumbers(Collections.singletonList("+13476547689"));
    client.getConfiguration().getContactPersons().add(person);
    final var uiInfo = new SAML2MetadataUIInfo();
    uiInfo.setDescriptions(Collections.singletonList("description1"));
    uiInfo.setDisplayNames(Collections.singletonList("displayName"));
    uiInfo.setPrivacyUrls(Collections.singletonList("https://pac4j.org"));
    uiInfo.setInformationUrls(Collections.singletonList("https://pac4j.org"));
    uiInfo.setKeywords(Collections.singletonList("keyword1,keyword2,keyword3"));
    uiInfo.setLogos(Collections.singletonList(new SAML2MetadataUIInfo.SAML2MetadataUILogo("https://pac4j.org/logo.png", 16, 16)));
    client.getConfiguration().getMetadataUIInfos().add(uiInfo);
    final var action = (OkAction) client.getRedirectionAction(MockWebContext.create(), new MockSessionStore()).get();
    final var issuerJdk11 = "<saml2:Issuer " + "xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\" " + "Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\" " + "NameQualifier=\"http://localhost:8080/cb\">http://localhost:8080/cb</saml2:Issuer>";
    final var decodedAuthnRequest = getDecodedAuthnRequest(action.getContent());
    assertTrue(decodedAuthnRequest.contains(issuerJdk11));
}
Also used : SAML2MetadataContactPerson(org.pac4j.saml.metadata.SAML2MetadataContactPerson) MockSessionStore(org.pac4j.core.context.session.MockSessionStore) SAML2MetadataUIInfo(org.pac4j.saml.metadata.SAML2MetadataUIInfo) OkAction(org.pac4j.core.exception.http.OkAction) Test(org.junit.Test)

Example 4 with OkAction

use of org.pac4j.core.exception.http.OkAction in project pac4j by pac4j.

the class JEEHttpActionAdapterTest method testActionWithContent.

@Test
public void testActionWithContent() {
    JEEHttpActionAdapter.INSTANCE.adapt(new OkAction(TestsConstants.VALUE), context);
    verify(response).setStatus(200);
    verify(writer).write(TestsConstants.VALUE);
}
Also used : OkAction(org.pac4j.core.exception.http.OkAction) Test(org.junit.Test)

Example 5 with OkAction

use of org.pac4j.core.exception.http.OkAction in project pac4j by pac4j.

the class OidcExtractor method extract.

@Override
public Optional<Credentials> extract(final WebContext context, final SessionStore sessionStore) {
    final var logoutEndpoint = context.getRequestParameter(Pac4jConstants.LOGOUT_ENDPOINT_PARAMETER).isPresent();
    if (logoutEndpoint) {
        final var logoutToken = context.getRequestParameter("logout_token");
        // back-channel logout
        if (logoutToken.isPresent()) {
            try {
                final var jwt = JWTParser.parse(logoutToken.get());
                // we should use the tokenValidator, but we can't as validation fails on missing claims: exp, iat...
                // final IDTokenClaimsSet claims = configuration.findTokenValidator().validate(jwt, null);
                // final String sid = (String) claims.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
                final var sid = (String) jwt.getJWTClaimsSet().getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
                logger.debug("Handling back-channel logout for sessionId: {}", sid);
                configuration.findLogoutHandler().destroySessionBack(context, sessionStore, sid);
            } catch (final java.text.ParseException e) {
                logger.error("Cannot validate JWT logout token", e);
                throw BadRequestAction.INSTANCE;
            }
        } else {
            final var sid = context.getRequestParameter(Pac4jConstants.OIDC_CLAIM_SESSIONID).orElse(null);
            logger.debug("Handling front-channel logout for sessionId: {}", sid);
            // front-channel logout
            configuration.findLogoutHandler().destroySessionFront(context, sessionStore, sid);
        }
        context.setResponseHeader("Cache-Control", "no-cache, no-store");
        context.setResponseHeader("Pragma", "no-cache");
        throw new OkAction("");
    } else {
        final var computedCallbackUrl = client.computeFinalCallbackUrl(context);
        final var parameters = retrieveParameters(context);
        AuthenticationResponse response;
        try {
            response = AuthenticationResponseParser.parse(new URI(computedCallbackUrl), parameters);
        } catch (final URISyntaxException | ParseException e) {
            throw new TechnicalException(e);
        }
        if (response instanceof AuthenticationErrorResponse) {
            logger.error("Bad authentication response, error={}", ((AuthenticationErrorResponse) response).getErrorObject());
            return Optional.empty();
        }
        logger.debug("Authentication response successful");
        var successResponse = (AuthenticationSuccessResponse) response;
        if (configuration.isWithState()) {
            // Validate state for CSRF mitigation
            final var requestState = (State) configuration.getValueRetriever().retrieve(client.getStateSessionAttributeName(), client, context, sessionStore).orElseThrow(() -> new TechnicalException("State cannot be determined"));
            final var responseState = successResponse.getState();
            if (responseState == null) {
                throw new TechnicalException("Missing state parameter");
            }
            logger.debug("Request state: {}/response state: {}", requestState, responseState);
            if (!requestState.equals(responseState)) {
                throw new TechnicalException("State parameter is different from the one sent in authentication request.");
            }
        }
        final var credentials = new OidcCredentials();
        // get authorization code
        final var code = successResponse.getAuthorizationCode();
        if (code != null) {
            credentials.setCode(code);
        }
        // get ID token
        final var idToken = successResponse.getIDToken();
        if (idToken != null) {
            credentials.setIdToken(idToken);
        }
        // get access token
        final var accessToken = successResponse.getAccessToken();
        if (accessToken != null) {
            credentials.setAccessToken(accessToken);
        }
        return Optional.of(credentials);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) URISyntaxException(java.net.URISyntaxException) AuthenticationResponse(com.nimbusds.openid.connect.sdk.AuthenticationResponse) URI(java.net.URI) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) State(com.nimbusds.oauth2.sdk.id.State) WebContext(org.pac4j.core.context.WebContext) ParseException(com.nimbusds.oauth2.sdk.ParseException) OkAction(org.pac4j.core.exception.http.OkAction)

Aggregations

OkAction (org.pac4j.core.exception.http.OkAction)8 Test (org.junit.Test)7 MockSessionStore (org.pac4j.core.context.session.MockSessionStore)5 WebContext (org.pac4j.core.context.WebContext)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)1 State (com.nimbusds.oauth2.sdk.id.State)1 AuthenticationErrorResponse (com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse)1 AuthenticationResponse (com.nimbusds.openid.connect.sdk.AuthenticationResponse)1 AuthenticationSuccessResponse (com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 MockWebContext (org.pac4j.core.context.MockWebContext)1 SessionStore (org.pac4j.core.context.session.SessionStore)1 TechnicalException (org.pac4j.core.exception.TechnicalException)1 OidcCredentials (org.pac4j.oidc.credentials.OidcCredentials)1 SAMLException (org.pac4j.saml.exceptions.SAMLException)1 SAML2MetadataContactPerson (org.pac4j.saml.metadata.SAML2MetadataContactPerson)1 SAML2MetadataUIInfo (org.pac4j.saml.metadata.SAML2MetadataUIInfo)1 SAML2ResponseValidator (org.pac4j.saml.profile.api.SAML2ResponseValidator)1