Search in sources :

Example 1 with OidcCredentials

use of org.pac4j.oidc.credentials.OidcCredentials in project pac4j by pac4j.

the class OidcExtractor method extract.

@Override
public OidcCredentials extract(final WebContext context) {
    final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
    final Map<String, String> 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 null;
    }
    logger.debug("Authentication response successful");
    AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response;
    final State state = successResponse.getState();
    if (state == null) {
        throw new TechnicalException("Missing state parameter");
    }
    if (!state.equals(context.getSessionStore().get(context, OidcConfiguration.STATE_SESSION_ATTRIBUTE))) {
        throw new TechnicalException("State parameter is different from the one sent in authentication request. " + "Session expired or possible threat of cross-site request forgery");
    }
    final OidcCredentials credentials = new OidcCredentials();
    // get authorization code
    final AuthorizationCode code = successResponse.getAuthorizationCode();
    if (code != null) {
        credentials.setCode(code);
    }
    // get ID token
    final JWT idToken = successResponse.getIDToken();
    if (idToken != null) {
        credentials.setIdToken(idToken);
    }
    // get access token
    final AccessToken accessToken = successResponse.getAccessToken();
    if (accessToken != null) {
        credentials.setAccessToken(accessToken);
    }
    return credentials;
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) State(com.nimbusds.oauth2.sdk.id.State) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException)

Example 2 with OidcCredentials

use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.

the class OidcHandler method getCredentialsFromRequest.

private OidcCredentials getCredentialsFromRequest(OidcClient<OidcConfiguration> oidcClient, JEEContext jeeContext) {
    // Check that the request contains a code, an access token or an id token
    Map<String, String[]> requestParams = jeeContext.getRequestParameters();
    if (!requestParams.containsKey("code") && !requestParams.containsKey("access_token") && !requestParams.containsKey("id_token")) {
        return new OidcCredentials();
    }
    oidcClient.setCallbackUrlResolver(new QueryParameterCallbackUrlResolver());
    OidcExtractor oidcExtractor = new OidcExtractor(oidcClient.getConfiguration(), oidcClient);
    return oidcExtractor.extract(jeeContext).orElse(null);
}
Also used : OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) OidcExtractor(org.pac4j.oidc.credentials.extractor.OidcExtractor) QueryParameterCallbackUrlResolver(org.pac4j.core.http.callback.QueryParameterCallbackUrlResolver)

Example 3 with OidcCredentials

use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.

the class OidcHandler method getNormalizedToken.

/**
 * Handler implementing OIDC authentication.
 *
 * @param request http request to obtain attributes from and to pass into any local filter chains
 *     required
 * @param response http response to return http responses or redirects
 * @param chain original filter chain (should not be called from your handler)
 * @param resolve flag with true implying that credentials should be obtained, false implying
 *     return if no credentials are found.
 * @return result of handling this request - status and optional tokens
 * @throws AuthenticationFailureException
 */
@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, SecurityFilterChain chain, boolean resolve) throws AuthenticationFailureException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if (httpRequest.getMethod().equals("HEAD")) {
        return processHeadRequest(httpResponse);
    }
    LOGGER.debug("Doing Oidc authentication and authorization for path {}.", httpRequest.getContextPath());
    JEESessionStore sessionStore = new JEESessionStore();
    JEEContext jeeContext = new JEEContext(httpRequest, httpResponse, sessionStore);
    StringBuffer requestUrlBuffer = httpRequest.getRequestURL();
    requestUrlBuffer.append(httpRequest.getQueryString() == null ? "" : "?" + httpRequest.getQueryString());
    String requestUrl = requestUrlBuffer.toString();
    String ipAddress = httpRequest.getRemoteAddr();
    OidcClient<OidcConfiguration> oidcClient = configuration.getOidcClient(requestUrl);
    OidcCredentials credentials;
    boolean isMachine = userAgentIsNotBrowser(httpRequest);
    if (isMachine) {
        LOGGER.debug("The Oidc Handler does not handle machine to machine requests. Continuing to other handlers.");
        return noActionResult;
    } else {
        // check for Authorization Code Flow, Implicit Flow, or Hybrid Flow credentials
        try {
            credentials = getCredentialsFromRequest(oidcClient, jeeContext);
        } catch (IllegalArgumentException e) {
            LOGGER.debug(e.getMessage(), e);
            LOGGER.error("Problem with the Oidc Handler's configuration. " + "Check the Oidc Handler configuration in the admin console.");
            return noActionResult;
        } catch (TechnicalException e) {
            LOGGER.debug("Problem extracting Oidc credentials from incoming user request.", e);
            return redirectForCredentials(oidcClient, jeeContext, requestUrl);
        }
    }
    // if the request has credentials, process it
    if (credentials != null && (credentials.getCode() != null || credentials.getAccessToken() != null || credentials.getIdToken() != null)) {
        LOGGER.info("Oidc credentials found/retrieved. Saving to session and continuing filter chain.");
        OidcAuthenticationToken token = new OidcAuthenticationToken(credentials, jeeContext, ipAddress);
        HandlerResult handlerResult = new HandlerResultImpl(Status.COMPLETED, token);
        handlerResult.setSource(SOURCE);
        return handlerResult;
    } else {
        // the user agent request didn't have credentials, redirect and go get some
        LOGGER.info("No credentials found on user-agent request. " + "Redirecting user-agent to IdP for credentials.");
        return redirectForCredentials(oidcClient, jeeContext, requestUrl);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) HandlerResultImpl(org.codice.ddf.security.handler.HandlerResultImpl) JEEContext(org.pac4j.core.context.JEEContext) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) JEESessionStore(org.pac4j.core.context.session.JEESessionStore) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials)

Example 4 with OidcCredentials

use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.

the class OidcLogoutActionProviderTest method testGetActionFailureWrongKey.

@Test
public void testGetActionFailureWrongKey() {
    OidcCredentials credentials = mock(OidcCredentials.class);
    Action action = oidcLogoutActionProvider.getAction(ImmutableMap.of("wrong key", credentials));
    assertNull(action);
}
Also used : OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) FoundAction(org.pac4j.core.exception.http.FoundAction) Action(ddf.action.Action) Test(org.junit.Test)

Example 5 with OidcCredentials

use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.

the class OidcLogoutActionProviderTest method testGetActionFailsWithoutRequestAndResponse.

@Test
public void testGetActionFailsWithoutRequestAndResponse() {
    OidcCredentials credentials = mock(OidcCredentials.class);
    Action action = oidcLogoutActionProvider.getAction(ImmutableMap.of(SecurityConstants.SECURITY_SUBJECT, credentials));
    assertNull(action);
}
Also used : OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) FoundAction(org.pac4j.core.exception.http.FoundAction) Action(ddf.action.Action) Test(org.junit.Test)

Aggregations

OidcCredentials (org.pac4j.oidc.credentials.OidcCredentials)10 OidcAuthenticationToken (org.codice.ddf.security.handler.OidcAuthenticationToken)5 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 WebContext (org.pac4j.core.context.WebContext)3 TechnicalException (org.pac4j.core.exception.TechnicalException)3 OidcConfiguration (org.pac4j.oidc.config.OidcConfiguration)3 JWT (com.nimbusds.jwt.JWT)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 OIDCProviderMetadata (com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata)2 Action (ddf.action.Action)2 URI (java.net.URI)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HandlerResultImpl (org.codice.ddf.security.handler.HandlerResultImpl)2 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)2 Test (org.junit.Test)2 JEEContext (org.pac4j.core.context.JEEContext)2 JEESessionStore (org.pac4j.core.context.session.JEESessionStore)2 FoundAction (org.pac4j.core.exception.http.FoundAction)2