Search in sources :

Example 1 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project nifi by apache.

the class AccessResource method oidcCallback.

@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("oidc/callback")
@ApiOperation(value = "Redirect/callback URI for processing the result of the OpenId Connect login sequence.", notes = NON_GUARANTEED_ENDPOINT)
public void oidcCallback(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) throws Exception {
    // only consider user specific access over https
    if (!httpServletRequest.isSecure()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "User authentication/authorization is only supported when running over HTTPS.");
        return;
    }
    // ensure oidc is enabled
    if (!oidcService.isOidcEnabled()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "OpenId Connect is not configured.");
        return;
    }
    final String oidcRequestIdentifier = getCookieValue(httpServletRequest.getCookies(), OIDC_REQUEST_IDENTIFIER);
    if (oidcRequestIdentifier == null) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "The login request identifier was not found in the request. Unable to continue.");
        return;
    }
    final com.nimbusds.openid.connect.sdk.AuthenticationResponse oidcResponse;
    try {
        oidcResponse = AuthenticationResponseParser.parse(getRequestUri());
    } catch (final ParseException e) {
        logger.error("Unable to parse the redirect URI from the OpenId Connect Provider. Unable to continue login process.");
        // remove the oidc request cookie
        removeOidcRequestCookie(httpServletResponse);
        // forward to the error page
        forwardToMessagePage(httpServletRequest, httpServletResponse, "Unable to parse the redirect URI from the OpenId Connect Provider. Unable to continue login process.");
        return;
    }
    if (oidcResponse.indicatesSuccess()) {
        final AuthenticationSuccessResponse successfulOidcResponse = (AuthenticationSuccessResponse) oidcResponse;
        // confirm state
        final State state = successfulOidcResponse.getState();
        if (state == null || !oidcService.isStateValid(oidcRequestIdentifier, state)) {
            logger.error("The state value returned by the OpenId Connect Provider does not match the stored state. Unable to continue login process.");
            // remove the oidc request cookie
            removeOidcRequestCookie(httpServletResponse);
            // forward to the error page
            forwardToMessagePage(httpServletRequest, httpServletResponse, "Purposed state does not match the stored state. Unable to continue login process.");
            return;
        }
        try {
            // exchange authorization code for id token
            final AuthorizationCode authorizationCode = successfulOidcResponse.getAuthorizationCode();
            final AuthorizationGrant authorizationGrant = new AuthorizationCodeGrant(authorizationCode, URI.create(getOidcCallback()));
            oidcService.exchangeAuthorizationCode(oidcRequestIdentifier, authorizationGrant);
        } catch (final Exception e) {
            logger.error("Unable to exchange authorization for ID token: " + e.getMessage(), e);
            // remove the oidc request cookie
            removeOidcRequestCookie(httpServletResponse);
            // forward to the error page
            forwardToMessagePage(httpServletRequest, httpServletResponse, "Unable to exchange authorization for ID token: " + e.getMessage());
            return;
        }
        // redirect to the name page
        httpServletResponse.sendRedirect("../../../nifi");
    } else {
        // remove the oidc request cookie
        removeOidcRequestCookie(httpServletResponse);
        // report the unsuccessful login
        final AuthenticationErrorResponse errorOidcResponse = (AuthenticationErrorResponse) oidcResponse;
        forwardToMessagePage(httpServletRequest, httpServletResponse, "Unsuccessful login attempt: " + errorOidcResponse.getErrorObject().getDescription());
    }
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) AuthenticationException(org.springframework.security.core.AuthenticationException) InvalidAuthenticationException(org.apache.nifi.web.security.InvalidAuthenticationException) AdministrationException(org.apache.nifi.admin.service.AdministrationException) UntrustedProxyException(org.apache.nifi.web.security.UntrustedProxyException) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) JwtException(io.jsonwebtoken.JwtException) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) State(com.nimbusds.oauth2.sdk.id.State) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 2 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project nifi by apache.

the class StandardOidcIdentityProvider method lookupEmail.

private String lookupEmail(final BearerAccessToken bearerAccessToken) throws IOException {
    try {
        // build the user request
        final UserInfoRequest request = new UserInfoRequest(oidcProviderMetadata.getUserInfoEndpointURI(), bearerAccessToken);
        final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
        tokenHttpRequest.setReadTimeout(oidcReadTimeout);
        // send the user request
        final UserInfoResponse response = UserInfoResponse.parse(request.toHTTPRequest().send());
        // interpret the details
        if (response.indicatesSuccess()) {
            final UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) response;
            final JWTClaimsSet claimsSet;
            if (successResponse.getUserInfo() != null) {
                claimsSet = successResponse.getUserInfo().toJWTClaimsSet();
            } else {
                claimsSet = successResponse.getUserInfoJWT().getJWTClaimsSet();
            }
            final String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
            // ensure we were able to get the user email
            if (StringUtils.isBlank(email)) {
                throw new IllegalStateException("Unable to extract email from the UserInfo token.");
            } else {
                return email;
            }
        } else {
            final UserInfoErrorResponse errorResponse = (UserInfoErrorResponse) response;
            throw new RuntimeException("An error occurred while invoking the UserInfo endpoint: " + errorResponse.getErrorObject().getDescription());
        }
    } catch (final ParseException | java.text.ParseException e) {
        throw new RuntimeException("Unable to parse the response from the UserInfo token request: " + e.getMessage());
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) UserInfoSuccessResponse(com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) UserInfoRequest(com.nimbusds.openid.connect.sdk.UserInfoRequest) ParseException(com.nimbusds.oauth2.sdk.ParseException) UserInfoResponse(com.nimbusds.openid.connect.sdk.UserInfoResponse)

Example 3 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project pac4j by pac4j.

the class OidcAuthenticator method validate.

@Override
public void validate(final OidcCredentials credentials, final WebContext context) {
    final AuthorizationCode code = credentials.getCode();
    // if we have a code
    if (code != null) {
        try {
            final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
            // Token request
            final TokenRequest request = new TokenRequest(configuration.findProviderMetadata().getTokenEndpointURI(), this.clientAuthentication, new AuthorizationCodeGrant(code, new URI(computedCallbackUrl)));
            HTTPRequest tokenHttpRequest = request.toHTTPRequest();
            tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = tokenHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
            if (response instanceof TokenErrorResponse) {
                throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
            }
            logger.debug("Token response successful");
            final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
            // save tokens in credentials
            final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
            credentials.setAccessToken(oidcTokens.getAccessToken());
            credentials.setRefreshToken(oidcTokens.getRefreshToken());
            credentials.setIdToken(oidcTokens.getIDToken());
        } catch (final URISyntaxException | IOException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens)

Example 4 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException 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 5 with ParseException

use of com.nimbusds.oauth2.sdk.ParseException in project pac4j by pac4j.

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
    init();
    final AccessToken accessToken = credentials.getAccessToken();
    // Create profile
    final U profile = getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        // check idToken
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
        } else {
            nonce = null;
        }
        // Check ID Token
        final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
            final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final JWTClaimsSet userInfoClaimsSet;
                if (userInfoSuccessResponse.getUserInfo() != null) {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
                } else {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
                }
                getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
            }
        }
        // add attributes of the ID token if they don't already exist
        for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // it's not the subject and this attribute does not already exist, add it
            if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
            }
        }
        return profile;
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Aggregations

ParseException (com.nimbusds.oauth2.sdk.ParseException)5 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)5 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)4 JWT (com.nimbusds.jwt.JWT)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)3 IOException (java.io.IOException)3 URI (java.net.URI)3 TechnicalException (org.pac4j.core.exception.TechnicalException)3 JOSEException (com.nimbusds.jose.JOSEException)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 State (com.nimbusds.oauth2.sdk.id.State)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)2 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)2 URISyntaxException (java.net.URISyntaxException)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1