Search in sources :

Example 6 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project ddf by codice.

the class OidcCredentialsResolver method trySendingGrantAndPopulatingCredentials.

private void trySendingGrantAndPopulatingCredentials(AuthorizationGrant grant, OidcCredentials credentials, WebContext webContext) throws IOException, ParseException {
    final OIDCTokens oidcTokens = getOidcTokens(grant);
    try {
        JWT idToken = oidcTokens.getIDToken();
        if (idToken != null) {
            OidcTokenValidator.validateIdTokens(idToken, webContext, configuration, client);
        }
        AccessToken accessToken = oidcTokens.getAccessToken();
        if (accessToken != null) {
            OidcTokenValidator.validateAccessToken(accessToken, idToken, resourceRetriever, metadata, configuration);
        }
        credentials.setAccessToken(accessToken);
        credentials.setIdToken(idToken);
        credentials.setRefreshToken(oidcTokens.getRefreshToken());
    } catch (OidcValidationException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException)

Example 7 with TechnicalException

use of org.pac4j.core.exception.TechnicalException 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 8 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class JwtAuthenticator method createJwtProfile.

@SuppressWarnings("unchecked")
protected void createJwtProfile(final TokenCredentials credentials, final JWT jwt) throws ParseException {
    final JWTClaimsSet claimSet = jwt.getJWTClaimsSet();
    String subject = claimSet.getSubject();
    if (subject == null) {
        throw new TechnicalException("JWT must contain a subject ('sub' claim)");
    }
    final Date expirationTime = claimSet.getExpirationTime();
    if (expirationTime != null) {
        final Date now = new Date();
        if (expirationTime.before(now)) {
            logger.error("The JWT is expired: no profile is built");
            return;
        }
    }
    final Map<String, Object> attributes = new HashMap<>(claimSet.getClaims());
    attributes.remove(JwtClaims.SUBJECT);
    final List<String> roles = (List<String>) attributes.get(JwtGenerator.INTERNAL_ROLES);
    attributes.remove(JwtGenerator.INTERNAL_ROLES);
    final List<String> permissions = (List<String>) attributes.get(JwtGenerator.INTERNAL_PERMISSIONS);
    attributes.remove(JwtGenerator.INTERNAL_PERMISSIONS);
    final CommonProfile profile = ProfileHelper.restoreOrBuildProfile(getProfileDefinition(), subject, attributes, null);
    if (roles != null) {
        profile.addRoles(roles);
    }
    if (permissions != null) {
        profile.addPermissions(permissions);
    }
    credentials.setUserProfile(profile);
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) HashMap(java.util.HashMap) CommonProfile(org.pac4j.core.profile.CommonProfile) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ArrayList(java.util.ArrayList) List(java.util.List) Date(java.util.Date)

Example 9 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class OAuth20RedirectActionBuilder method redirect.

@Override
public RedirectAction redirect(final WebContext context) {
    try {
        final OAuth20Service service;
        // with state: generate a state, save it in session and build a new service with this state
        if (this.configuration.isWithState()) {
            final String state = getStateParameter();
            logger.debug("save sessionState: {}", state);
            context.getSessionStore().set(context, this.configuration.getStateSessionAttributeName(client.getName()), state);
            service = this.configuration.buildService(context, client, state);
        } else {
            service = this.configuration.buildService(context, client, null);
        }
        final String authorizationUrl = service.getAuthorizationUrl(this.configuration.getCustomParams());
        logger.debug("authorizationUrl: {}", authorizationUrl);
        return RedirectAction.redirect(authorizationUrl);
    } catch (final OAuthException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) OAuthException(com.github.scribejava.core.exceptions.OAuthException) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service)

Example 10 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class SAML2Client method initChainingMetadataResolver.

protected ChainingMetadataResolver initChainingMetadataResolver(final MetadataResolver idpMetadataProvider, final MetadataResolver spMetadataProvider) {
    final ChainingMetadataResolver metadataManager = new ChainingMetadataResolver();
    metadataManager.setId(ChainingMetadataResolver.class.getCanonicalName());
    try {
        final List<MetadataResolver> list = new ArrayList<>();
        list.add(idpMetadataProvider);
        list.add(spMetadataProvider);
        metadataManager.setResolvers(list);
        metadataManager.initialize();
    } catch (final ResolverException e) {
        throw new TechnicalException("Error adding idp or sp metadatas to manager", e);
    } catch (final ComponentInitializationException e) {
        throw new TechnicalException("Error initializing manager", e);
    }
    return metadataManager;
}
Also used : ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) ResolverException(net.shibboleth.utilities.java.support.resolver.ResolverException) TechnicalException(org.pac4j.core.exception.TechnicalException) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) ArrayList(java.util.ArrayList) SAML2IdentityProviderMetadataResolver(org.pac4j.saml.metadata.SAML2IdentityProviderMetadataResolver) SAML2ServiceProviderMetadataResolver(org.pac4j.saml.metadata.SAML2ServiceProviderMetadataResolver) SAML2MetadataResolver(org.pac4j.saml.metadata.SAML2MetadataResolver) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver)

Aggregations

TechnicalException (org.pac4j.core.exception.TechnicalException)81 IOException (java.io.IOException)26 URI (java.net.URI)7 URISyntaxException (java.net.URISyntaxException)7 HashMap (java.util.HashMap)7 OAuthException (com.github.scribejava.core.exceptions.OAuthException)6 JWT (com.nimbusds.jwt.JWT)6 ParseException (com.nimbusds.oauth2.sdk.ParseException)6 HttpURLConnection (java.net.HttpURLConnection)6 Test (org.junit.Test)6 OidcCredentials (org.pac4j.oidc.credentials.OidcCredentials)6 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)5 SignedJWT (com.nimbusds.jwt.SignedJWT)5 ArrayList (java.util.ArrayList)5 ComponentInitializationException (net.shibboleth.utilities.java.support.component.ComponentInitializationException)5 JOSEException (com.nimbusds.jose.JOSEException)4 URL (java.net.URL)4 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)3 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)3 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)3