Search in sources :

Example 6 with OidcCredentials

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

the class OidcRealm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // token is guaranteed to be of type OidcAuthenticationToken by the supports() method
    OidcAuthenticationToken oidcAuthenticationToken = (OidcAuthenticationToken) authenticationToken;
    OidcCredentials credentials = (OidcCredentials) oidcAuthenticationToken.getCredentials();
    OidcConfiguration oidcConfiguration = oidcHandlerConfiguration.getOidcConfiguration();
    OIDCProviderMetadata oidcProviderMetadata = oidcConfiguration.findProviderMetadata();
    WebContext webContext = (WebContext) oidcAuthenticationToken.getContext();
    OidcClient<OidcConfiguration> oidcClient = oidcHandlerConfiguration.getOidcClient(webContext.getFullRequestURL());
    int connectTimeout = oidcHandlerConfiguration.getConnectTimeout();
    int readTimeout = oidcHandlerConfiguration.getReadTimeout();
    try {
        OidcCredentialsResolver oidcCredentialsResolver = new OidcCredentialsResolver(oidcConfiguration, oidcClient, oidcProviderMetadata, connectTimeout, readTimeout);
        oidcCredentialsResolver.resolveIdToken(credentials, webContext);
    } catch (TechnicalException e) {
        throw new AuthenticationException(e);
    }
    // problem getting id token, invalidate credentials
    if (credentials.getIdToken() == null) {
        webContext.getSessionStore().destroySession(webContext);
        String msg = String.format("Could not fetch id token with Oidc credentials (%s). " + "This may be due to the credentials expiring. " + "Invalidating session in order to acquire valid credentials.", credentials);
        LOGGER.warn(msg);
        throw new AuthenticationException(msg);
    }
    OidcProfileCreator oidcProfileCreator = new CustomOidcProfileCreator(oidcConfiguration, oidcClient);
    Optional<UserProfile> userProfile = oidcProfileCreator.create(credentials, webContext);
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    simpleAuthenticationInfo.setCredentials(credentials);
    if (userProfile.isPresent()) {
        OidcProfile oidcProfile = (OidcProfile) userProfile.get();
        simpleAuthenticationInfo.setPrincipals(createPrincipalCollectionFromCredentials(oidcProfile));
    } else {
        simpleAuthenticationInfo.setPrincipals(new SimplePrincipalCollection());
    }
    return simpleAuthenticationInfo;
}
Also used : WebContext(org.pac4j.core.context.WebContext) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) OidcCredentialsResolver(org.codice.ddf.security.oidc.resolver.OidcCredentialsResolver) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) OidcProfileCreator(org.pac4j.oidc.profile.creator.OidcProfileCreator) OidcProfile(org.pac4j.oidc.profile.OidcProfile) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata)

Example 7 with OidcCredentials

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

the class OidcRealm method supports.

/**
 * Determine if the supplied token is supported by this realm.
 */
@Override
public boolean supports(AuthenticationToken token) {
    if (!(token instanceof OidcAuthenticationToken)) {
        LOGGER.debug("The supplied authentication token is not an instance of SessionToken or OidcAuthenticationToken. Sending back not supported.");
        return false;
    }
    OidcAuthenticationToken oidcToken = (OidcAuthenticationToken) token;
    OidcCredentials credentials = (OidcCredentials) oidcToken.getCredentials();
    if (credentials == null || (credentials.getCode() == null && credentials.getAccessToken() == null && credentials.getIdToken() == null)) {
        LOGGER.debug("The supplied authentication token has null/empty credentials. Sending back no supported.");
        return false;
    }
    WebContext webContext = (WebContext) oidcToken.getContext();
    if (webContext == null) {
        LOGGER.debug("The supplied authentication token has null web context. Sending back not supported.");
        return false;
    }
    LOGGER.debug("Token {} is supported by {}.", token.getClass(), OidcRealm.class.getName());
    return true;
}
Also used : OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) WebContext(org.pac4j.core.context.WebContext) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken)

Example 8 with OidcCredentials

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

the class CustomOAuthCredentialsExtractor method getOauthCredentialsAsOidcCredentials.

public OidcCredentials getOauthCredentialsAsOidcCredentials(final WebContext context) {
    OidcCredentials credentials = new OidcCredentials();
    try {
        final String codeParam = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE).orElse(null);
        if (codeParam != null) {
            credentials.setCode(new AuthorizationCode(URLDecoder.decode(codeParam, StandardCharsets.UTF_8.name())));
        } else {
            LOGGER.debug("No OAuth2 code found on request.");
        }
        final String accessTokenParam = context.getRequestParameter("access_token").orElse(null);
        final String accessTokenHeader = getAccessTokenFromHeader(context);
        final String accessToken = accessTokenParam != null ? accessTokenParam : accessTokenHeader;
        if (isNotBlank(accessToken)) {
            credentials.setAccessToken(new BearerAccessToken(URLDecoder.decode(accessToken, StandardCharsets.UTF_8.name())));
        } else {
            LOGGER.debug("No OAuth2 access token found on request.");
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.debug("Error decoding the authorization code/access token from url parameters.", e);
    }
    return credentials;
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken)

Example 9 with OidcCredentials

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

the class OAuthHandler method getNormalizedToken.

@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);
    }
    JEESessionStore sessionStore = new JEESessionStore();
    JEEContext jeeContext = new JEEContext(httpRequest, httpResponse, sessionStore);
    // time to try and pull credentials off of the request
    LOGGER.debug("Doing OAuth authentication and authorization for path {}.", httpRequest.getContextPath());
    OidcCredentials credentials;
    StringBuffer requestUrlBuffer = httpRequest.getRequestURL();
    requestUrlBuffer.append(httpRequest.getQueryString() == null ? "" : "?" + httpRequest.getQueryString());
    String ipAddress = httpRequest.getRemoteAddr();
    boolean isMachine = userAgentIsNotBrowser(httpRequest);
    // machine to machine, check for Client Credentials Flow credentials
    if (isMachine) {
        try {
            credentials = getCredentialsFromRequest(jeeContext);
        } catch (IllegalArgumentException e) {
            LOGGER.error("Problem with the OAuth Handler's OAuthHandlerConfiguration. " + "Check the OAuth Handler Configuration in the admin console.", e);
            return noActionResult;
        } catch (OAuthCredentialsException e) {
            LOGGER.error("Problem extracting credentials from machine to machine request. " + "See OAuth2's \"Client Credential Flow\" for more information.", e);
            return noActionResult;
        }
    } else {
        LOGGER.info("The OAuth Handler does not handle user agent requests. Continuing to other handlers.");
        return noActionResult;
    }
    // if the request has credentials, process it
    if (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 {
        LOGGER.info("No credentials found on user-agent request. " + "This handler does not support the acquisition of user agent credentials. Continuing to other handlers.");
        return noActionResult;
    }
}
Also used : 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) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) OAuthCredentialsException(org.pac4j.oauth.exception.OAuthCredentialsException)

Example 10 with OidcCredentials

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

the class OidcRealmTest method setup.

@Before
public void setup() throws Exception {
    realm = new OidcRealm();
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    OIDCProviderMetadata oidcProviderMetadata = mock(OIDCProviderMetadata.class);
    when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
    when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
    when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
    ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
    Resource resource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
    OidcConfiguration configuration = mock(OidcConfiguration.class);
    when(configuration.getClientId()).thenReturn("ddf-client");
    when(configuration.getSecret()).thenReturn("secret");
    when(configuration.isUseNonce()).thenReturn(true);
    when(configuration.getResponseType()).thenReturn("code");
    when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
    when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
    OidcHandlerConfiguration handlerConfiguration = mock(OidcHandlerConfiguration.class);
    when(handlerConfiguration.getOidcConfiguration()).thenReturn(configuration);
    when(handlerConfiguration.getOidcClient(any())).thenReturn(mock(OidcClient.class));
    realm.setOidcHandlerConfiguration(handlerConfiguration);
    realm.setUsernameAttributeList(Collections.singletonList("preferred_username"));
    JWT jwt = mock(JWT.class);
    AccessToken accessToken = new BearerAccessToken(getAccessTokenBuilder().sign(validAlgorithm));
    AuthorizationCode authorizationCode = new AuthorizationCode();
    WebContext webContext = getWebContext();
    oidcCredentials = mock(OidcCredentials.class);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getAccessToken()).thenReturn(accessToken);
    when(oidcCredentials.getCode()).thenReturn(authorizationCode);
    authenticationToken = mock(OidcAuthenticationToken.class);
    when(authenticationToken.getCredentials()).thenReturn(oidcCredentials);
    when(authenticationToken.getContext()).thenReturn(webContext);
}
Also used : OidcHandlerConfiguration(org.codice.ddf.security.handler.api.OidcHandlerConfiguration) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) WebContext(org.pac4j.core.context.WebContext) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Resource(com.nimbusds.jose.util.Resource) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) KeyPairGenerator(java.security.KeyPairGenerator) URI(java.net.URI) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) RSAPublicKey(java.security.interfaces.RSAPublicKey) OidcClient(org.pac4j.oidc.client.OidcClient) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

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