Search in sources :

Example 6 with AuthorizationGrant

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

the class OidcCredentialsResolver method resolveIdToken.

/* This methods job is to try and get an id token from a
  1. refresh token
  2. authorization code
  3. access token
  */
public void resolveIdToken(OidcCredentials credentials, WebContext webContext) {
    final AccessToken initialAccessToken = credentials.getAccessToken();
    final JWT initialIdToken = credentials.getIdToken();
    try {
        OidcTokenValidator.validateAccessToken(initialAccessToken, initialIdToken, resourceRetriever, metadata, configuration);
        if (initialIdToken != null) {
            OidcTokenValidator.validateIdTokens(initialIdToken, webContext, configuration, client);
            return;
        }
    } catch (OidcValidationException e) {
        throw new TechnicalException(e);
    }
    final RefreshToken initialRefreshToken = credentials.getRefreshToken();
    final AuthorizationCode initialAuthorizationCode = credentials.getCode();
    final List<AuthorizationGrant> grantList = new ArrayList<>();
    if (initialRefreshToken != null) {
        grantList.add(new RefreshTokenGrant(initialRefreshToken));
    }
    if (initialAuthorizationCode != null) {
        try {
            final URI callbackUri = new URI(client.computeFinalCallbackUrl(webContext));
            grantList.add(new AuthorizationCodeGrant(initialAuthorizationCode, callbackUri));
        } catch (URISyntaxException e) {
            LOGGER.debug("Problem computing callback url. Cannot add authorization code grant.");
        }
    }
    // try to get id token using refresh token and authorization code
    for (AuthorizationGrant grant : grantList) {
        try {
            trySendingGrantAndPopulatingCredentials(grant, credentials, webContext);
            if (credentials.getIdToken() != null) {
                break;
            }
        } catch (IOException | ParseException e) {
            LOGGER.debug("Problem sending grant ({}).", grant, e);
        }
    }
    // try to get id token using access token
    if (credentials.getIdToken() == null && initialAccessToken != null) {
        final UserInfoRequest userInfoRequest = new UserInfoRequest(metadata.getUserInfoEndpointURI(), Method.GET, new BearerAccessToken(initialAccessToken.toString()));
        final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
        try {
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoSuccessResponse) {
                final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                JWT idToken = userInfoSuccessResponse.getUserInfoJWT();
                if (idToken == null && userInfoSuccessResponse.getUserInfo().toJWTClaimsSet() != null) {
                    idToken = new PlainJWT(userInfoSuccessResponse.getUserInfo().toJWTClaimsSet());
                }
                OidcTokenValidator.validateUserInfoIdToken(idToken, resourceRetriever, metadata);
                credentials.setIdToken(idToken);
            } else {
                throw new TechnicalException("Received a non-successful UserInfoResponse.");
            }
        } catch (IOException | ParseException | OidcValidationException e) {
            LOGGER.debug("Problem retrieving id token using access token.", e);
            throw new TechnicalException(e);
        }
    }
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) PlainJWT(com.nimbusds.jwt.PlainJWT) TechnicalException(org.pac4j.core.exception.TechnicalException) UserInfoSuccessResponse(com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) RefreshTokenGrant(com.nimbusds.oauth2.sdk.RefreshTokenGrant) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) ArrayList(java.util.ArrayList) UserInfoRequest(com.nimbusds.openid.connect.sdk.UserInfoRequest) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) UserInfoResponse(com.nimbusds.openid.connect.sdk.UserInfoResponse) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant)

Example 7 with AuthorizationGrant

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

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    // Build the authorization code grant request for the token endpoint
    AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
    URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
    URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
    // Set the credentials to authenticate the client at the token endpoint
    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
    ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
    com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
    if (!tokenResponse.indicatesSuccess()) {
        TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
        ErrorObject errorObject = tokenErrorResponse.getErrorObject();
        throw new OAuth2AuthorizationException(getOAuthError(errorObject));
    }
    AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
    String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }
    long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
    // As per spec, in section 5.1 Successful Access Token Response
    // https://tools.ietf.org/html/rfc6749#section-5.1
    // If AccessTokenResponse.scope is empty, then default to the scope
    // originally requested by the client in the Authorization Request
    Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
    String refreshToken = null;
    if (accessTokenResponse.getTokens().getRefreshToken() != null) {
        refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
    }
    Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
    // @formatter:off
    return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
Also used : URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) LinkedHashMap(java.util.LinkedHashMap) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Example 8 with AuthorizationGrant

use of com.nimbusds.oauth2.sdk.AuthorizationGrant in project iaf by ibissource.

the class OAuthAccessTokenManager method createRequest.

private TokenRequest createRequest(Credentials credentials) throws HttpAuthenticationException {
    AuthorizationGrant grant;
    if (useClientCredentialsGrant) {
        grant = new ClientCredentialsGrant();
    } else {
        String username = credentials.getUserPrincipal().getName();
        Secret password = new Secret(credentials.getPassword());
        grant = new ResourceOwnerPasswordCredentialsGrant(username, password);
    }
    // The credentials to authenticate the client at the token endpoint
    ClientID clientID = new ClientID(client_cf.getUsername());
    Secret clientSecret = new Secret(client_cf.getPassword());
    ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
    try {
        URI _tokenEndpoint = new URI(tokenEndpoint);
        return new TokenRequest(_tokenEndpoint, clientAuth, grant, scope);
    } catch (URISyntaxException e) {
        throw new HttpAuthenticationException("illegal token endpoint", e);
    }
}
Also used : Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientCredentialsGrant(com.nimbusds.oauth2.sdk.ClientCredentialsGrant) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ResourceOwnerPasswordCredentialsGrant(com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) URISyntaxException(java.net.URISyntaxException) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)

Aggregations

AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)4 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)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 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)3 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)3 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)3 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)3 URI (java.net.URI)3 PlainJWT (com.nimbusds.jwt.PlainJWT)2 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)2 ClientSecretPost (com.nimbusds.oauth2.sdk.auth.ClientSecretPost)2 Secret (com.nimbusds.oauth2.sdk.auth.Secret)2 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2