Search in sources :

Example 1 with AuthorizationGrant

use of com.nimbusds.oauth2.sdk.AuthorizationGrant 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 AuthorizationGrant

use of com.nimbusds.oauth2.sdk.AuthorizationGrant in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

private com.nimbusds.oauth2.sdk.TokenResponse getTokenResponse(AuthorizationGrant authorizationCodeGrant, URI tokenUri, ClientAuthentication clientAuthentication) {
    try {
        // Send the Access Token request
        TokenRequest tokenRequest = new TokenRequest(tokenUri, clientAuthentication, authorizationCodeGrant);
        HTTPRequest httpRequest = tokenRequest.toHTTPRequest();
        httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
        httpRequest.setConnectTimeout(30000);
        httpRequest.setReadTimeout(30000);
        return com.nimbusds.oauth2.sdk.TokenResponse.parse(httpRequest.send());
    } catch (ParseException | IOException ex) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null);
        throw new OAuth2AuthorizationException(oauth2Error, ex);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ParseException(com.nimbusds.oauth2.sdk.ParseException) IOException(java.io.IOException)

Example 3 with AuthorizationGrant

use of com.nimbusds.oauth2.sdk.AuthorizationGrant in project ddf by codice.

the class OidcCredentialsResolver method getOidcTokens.

public static OIDCTokens getOidcTokens(AuthorizationGrant grant, OIDCProviderMetadata metadata, ClientAuthentication clientAuthentication, int connectTimeout, int readTimeout) throws IOException, ParseException {
    final TokenRequest request = new TokenRequest(metadata.getTokenEndpointURI(), clientAuthentication, grant);
    HTTPRequest tokenHttpRequest = request.toHTTPRequest();
    tokenHttpRequest.setConnectTimeout(connectTimeout);
    tokenHttpRequest.setReadTimeout(readTimeout);
    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;
    return tokenSuccessResponse.getOIDCTokens();
}
Also used : TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest)

Example 4 with AuthorizationGrant

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

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

the class StandardOidcIdentityProvider method exchangeAuthorizationCode.

@Override
public String exchangeAuthorizationCode(final AuthorizationGrant authorizationGrant) throws IOException {
    if (!isOidcEnabled()) {
        throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
    }
    final ClientAuthentication clientAuthentication;
    if (oidcProviderMetadata.getTokenEndpointAuthMethods().contains(ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
        clientAuthentication = new ClientSecretPost(clientId, clientSecret);
    } else {
        clientAuthentication = new ClientSecretBasic(clientId, clientSecret);
    }
    try {
        // build the token request
        final TokenRequest request = new TokenRequest(oidcProviderMetadata.getTokenEndpointURI(), clientAuthentication, authorizationGrant, getScope());
        final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
        tokenHttpRequest.setReadTimeout(oidcReadTimeout);
        // get the token response
        final TokenResponse response = OIDCTokenResponseParser.parse(tokenHttpRequest.send());
        if (response.indicatesSuccess()) {
            final OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) response;
            final OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
            final JWT oidcJwt = oidcTokens.getIDToken();
            // validate the token - no nonce required for authorization code flow
            final IDTokenClaimsSet claimsSet = tokenValidator.validate(oidcJwt, null);
            // attempt to extract the email from the id token if possible
            String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
            if (StringUtils.isBlank(email)) {
                // extract the bearer access token
                final BearerAccessToken bearerAccessToken = oidcTokens.getBearerAccessToken();
                if (bearerAccessToken == null) {
                    throw new IllegalStateException("No access token found in the ID tokens");
                }
                // invoke the UserInfo endpoint
                email = lookupEmail(bearerAccessToken);
            }
            // extract expiration details from the claims set
            final Calendar now = Calendar.getInstance();
            final Date expiration = claimsSet.getExpirationTime();
            final long expiresIn = expiration.getTime() - now.getTimeInMillis();
            // convert into a nifi jwt for retrieval later
            final LoginAuthenticationToken loginToken = new LoginAuthenticationToken(email, email, expiresIn, claimsSet.getIssuer().getValue());
            return jwtService.generateSignedToken(loginToken);
        } else {
            final TokenErrorResponse errorResponse = (TokenErrorResponse) response;
            throw new RuntimeException("An error occurred while invoking the Token endpoint: " + errorResponse.getErrorObject().getDescription());
        }
    } catch (final ParseException | JOSEException | BadJOSEException e) {
        throw new RuntimeException("Unable to parse the response from the Token request: " + e.getMessage());
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) JWT(com.nimbusds.jwt.JWT) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) Calendar(java.util.Calendar) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Date(java.util.Date) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Aggregations

ParseException (com.nimbusds.oauth2.sdk.ParseException)4 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)4 JWT (com.nimbusds.jwt.JWT)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)3 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)3 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)3 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)3 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)3 TechnicalException (org.pac4j.core.exception.TechnicalException)3 PlainJWT (com.nimbusds.jwt.PlainJWT)2 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)2 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)2 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)2 ClientSecretPost (com.nimbusds.oauth2.sdk.auth.ClientSecretPost)2 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)2 IOException (java.io.IOException)2