Search in sources :

Example 1 with AMGateway

use of com.forgerock.openbanking.am.gateway.AMGateway in project openbanking-aspsp by OpenBankingToolkit.

the class AuthorisationApiController method getAuthorisation.

/**
 * getAuthorisation - Implementation of the /authorize OIDC Connect endpoint.
 * @param responseType required = true
 * @param clientId required = true
 * @param state required = false
 * @param nonce required = false
 * @param scopes required = false
 * @param redirectUri required = false,
 * @param requestParametersSerialised required = true)
 * @param isHeadlessEnabled required = false, defaultValue = "false"
 * @param username required = false, defaultValue = ""
 * @param password required = false, defaultValue = ""
 * @param ssoToken (required = false)
 * @param body required = false
 * @return A <code>ResponseEntity</code> containing the result of authorization request
 * @throws OBErrorResponseException or OBErrorException when errors occur that prevent authorization
 */
@Override
public ResponseEntity getAuthorisation(String responseType, String clientId, String state, String nonce, String scopes, String redirectUri, String requestParametersSerialised, boolean isHeadlessEnabled, String username, String password, String ssoToken, MultiValueMap body, HttpServletRequest request) throws OBErrorResponseException, OBErrorException {
    // Initialisation the response entity, it will be overwritten with am response.
    ResponseEntity responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    try {
        // FAPI compliant ('code id_token'): https://github.com/ForgeCloud/ob-deploy/issues/674
        if (!discoveryConfig.getSupportedResponseTypes().contains(responseType)) {
            log.error("The response types requested '" + responseType + "' don't match with the response types " + "supported '" + discoveryConfig.getSupportedResponseTypes() + "' by as-api");
            throw new OBErrorResponseException(OBRIErrorType.REQUEST_RESPONSE_TYPE_MISMATCH.getHttpStatus(), OBRIErrorResponseCategory.REQUEST_INVALID, OBRIErrorType.REQUEST_RESPONSE_TYPE_MISMATCH.toOBError1(responseType, discoveryConfig.getSupportedResponseTypes().toString()));
        }
        SignedJWT requestParameterJwt = validateRequestParameter(responseType, clientId, state, nonce, scopes, redirectUri, requestParametersSerialised);
        requestParametersSerialised = requestParameterJwt.serialize();
        try {
            state = getState(state, requestParameterJwt);
        } catch (ParseException e) {
            throw new OBErrorResponseException(OBRIErrorType.REQUEST_PARAMETER_JWT_INVALID.getHttpStatus(), OBRIErrorResponseCategory.REQUEST_INVALID, OBRIErrorType.REQUEST_PARAMETER_JWT_INVALID.toOBError1(e.getMessage()));
        }
        AMGateway amGateway = amGatewayService.getAmGateway(requestParametersSerialised);
        if (isHeadlessAlwaysEnabled || isHeadlessEnabled) {
            log.debug("getAuthorisation() performing headless authorisation");
            responseEntity = headLessAuthorisationService.getAuthorisation(amGateway, responseType, clientId, state, nonce, scopes, redirectUri, requestParametersSerialised, username, password);
        } else {
            log.debug("getAuthorisation() delegating authorisation to AM");
            HashMap<String, String> queryParameters = new HashMap<>();
            queryParameters.put("request", requestParametersSerialised);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Cookie", cookieName + "=" + ssoToken);
            responseEntity = amGateway.toAM(request, httpHeaders, queryParameters, new ParameterizedTypeReference<String>() {
            }, body);
        }
        log.debug("getAuthorisation() responseEntity {}", responseEntity);
        // re-write it to appear as a fragment
        if (hasQueryParamIdToken(responseEntity)) {
            responseEntity = convertQueryToFragment(responseEntity.getHeaders().getLocation(), responseEntity.getHeaders(), state);
            return responseEntity;
        }
        // Rewriting the response as we need to re-sign the id token. We can assume the id_token will exist as a fragment
        if (hasFragmentIdToken(responseEntity)) {
            try {
                responseEntity = this.jwtOverridingService.rewriteIdTokenFragmentInLocationHeader(responseEntity);
                tokenUsageService.incrementTokenUsage(TokenUsage.ID_TOKEN);
            } catch (AccessTokenReWriteException e) {
                String supportUID = UUID.randomUUID().toString();
                log.info("getAuthorisation() Failed to re-write the id_token", e);
                throw new OBErrorResponseException(OBRIErrorType.AUTHORIZE_INVALID_ID_TOKEN.getHttpStatus(), OBRIErrorResponseCategory.ACCESS_TOKEN, OBRIErrorType.AUTHORIZE_INVALID_ID_TOKEN.toOBError1(supportUID));
            }
        } else {
            log.debug("responseEntity {} is null or is not a redirection", responseEntity);
        }
    } catch (OBErrorResponseException | OBErrorException obException) {
        log.error("Authorisation error '{}', building the redirect action", obException.getMessage());
        if (redirectUri != null && state != null) {
            RedirectionAction redirectionAction = buildRedirectionAction(obException, redirectUri, state);
            return ResponseEntity.status(HttpStatus.FOUND).header("Location", redirectionAction.getRedirectUri()).build();
        }
    }
    return responseEntity;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) RedirectionAction(com.forgerock.openbanking.common.model.rcs.RedirectionAction) OBErrorException(com.forgerock.openbanking.exceptions.OBErrorException) SignedJWT(com.nimbusds.jwt.SignedJWT) ResponseEntity(org.springframework.http.ResponseEntity) AMGateway(com.forgerock.openbanking.am.gateway.AMGateway) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) AccessTokenReWriteException(com.forgerock.openbanking.common.error.exception.AccessTokenReWriteException) ParseException(java.text.ParseException)

Example 2 with AMGateway

use of com.forgerock.openbanking.am.gateway.AMGateway in project openbanking-aspsp by OpenBankingToolkit.

the class AuthorisationApiControllerTest method shouldGetAuthorisationGivenAllScopes.

@Test
public void shouldGetAuthorisationGivenAllScopes() throws OBErrorException, OBErrorResponseException, InvalidTokenException, ParseException, IOException {
    // Given
    String clientId = "98e119f6-196f-4296-98d4-f1a2f445bca2";
    List<String> responseTypes = List.of("code id_token");
    given(discoveryConfig.getSupportedResponseTypes()).willReturn(responseTypes);
    String jwt = toEncodedSignedTestJwt("jwt/authorisation.jwt");
    Tpp tpp = new Tpp();
    OIDCRegistrationResponse registrationResponse = new OIDCRegistrationResponse();
    registrationResponse.setJwks_uri("url");
    tpp.setRegistrationResponse(registrationResponse);
    given(tppStoreService.findByClientId(clientId)).willReturn(Optional.of(tpp));
    SignedJWT signedJwt = mock(SignedJWT.class);
    given(cryptoApiClient.validateJws(anyString(), anyString(), anyString())).willReturn(signedJwt);
    AMGateway amGateway = mock(AMGateway.class);
    given(amGatewayService.getAmGateway(jwt)).willReturn(amGateway);
    String state = "10d260bf-a7d9-444a-92d9-7b7a5f088208";
    String scopes = "openid accounts payments";
    given(headLessAuthorisationService.getAuthorisation(amGateway, responseTypes.get(0), clientId, state, null, scopes, null, jwt, null, null)).willReturn(new ResponseEntity(HttpStatus.FOUND));
    // When
    ResponseEntity responseEntity = authorisationApiController.getAuthorisation(responseTypes.get(0), clientId, null, null, scopes, null, jwt, true, null, null, null, null, null);
    // Then no exception
    assertThat(responseEntity).isNotNull();
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.FOUND);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) Tpp(com.forgerock.openbanking.model.Tpp) AMGateway(com.forgerock.openbanking.am.gateway.AMGateway) OIDCRegistrationResponse(com.forgerock.openbanking.model.oidc.OIDCRegistrationResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.Test)

Example 3 with AMGateway

use of com.forgerock.openbanking.am.gateway.AMGateway in project openbanking-aspsp by OpenBankingToolkit.

the class AccessTokenApiController method getAccessToken.

@Override
@PreAuthorize("hasAnyAuthority('ROLE_PISP', 'ROLE_AISP', 'ROLE_CBPII')")
public ResponseEntity getAccessToken(MultiValueMap<String, String> paramMap, String authorization, Principal principal, HttpServletRequest request) throws OBErrorResponseException, OBErrorException {
    log.debug("getAccessToken(), paramMap {}", paramMap);
    PairClientIDAuthMethod clientIDAuthMethod = matlsRequestVerificationService.verifyMATLSMatchesRequest(paramMap, authorization, principal);
    AMGateway amGateway = this.amGateway;
    // The token endpoint can also be used as audience, as per OIDC spec
    if (clientIDAuthMethod.getAuthMethod() == PRIVATE_KEY_JWT) {
        String clientAssertion = paramMap.getFirst(CLIENT_ASSERTION);
        if (clientAssertion == null || clientAssertion.isBlank()) {
            log.debug("getAccessToken() clientAssertion was null or blank");
            throw new OBErrorResponseException(OBRIErrorType.ACCESS_TOKEN_INVALID.getHttpStatus(), OBRIErrorResponseCategory.ACCESS_TOKEN, OBRIErrorType.ACCESS_TOKEN_INVALID.toOBError1("No client_assertion in body"));
        }
        amGateway = amGatewayService.getAmGateway(clientAssertion);
    }
    // can throw a UnsupportedOIDCGrantTypeException
    GrantType grantType = GrantType.fromType(paramMap.getFirst(OIDCConstants.OIDCClaim.GRANT_TYPE));
    ResponseEntity<AccessTokenResponse> responseEntity = getAccessToken(paramMap, request, clientIDAuthMethod, amGateway, grantType);
    try {
        responseEntity = jwtOverridingService.rewriteAccessTokenResponseIdToken(responseEntity);
    } catch (AccessTokenReWriteException e) {
        log.debug("Failed to rewrite the access token response's id_token.", e);
        String supportUID = UUID.randomUUID().toString();
        throw new OBErrorResponseException(OBRIErrorType.ACCESS_TOKEN_INVALID_ID_TOKEN.getHttpStatus(), OBRIErrorResponseCategory.ACCESS_TOKEN, OBRIErrorType.ACCESS_TOKEN_INVALID_ID_TOKEN.toOBError1(supportUID));
    }
    return responseEntity;
}
Also used : AMGateway(com.forgerock.openbanking.am.gateway.AMGateway) OBErrorResponseException(com.forgerock.openbanking.exceptions.OBErrorResponseException) AccessTokenReWriteException(com.forgerock.openbanking.common.error.exception.AccessTokenReWriteException) GrantType(com.forgerock.openbanking.constants.OIDCConstants.GrantType) AccessTokenResponse(com.forgerock.openbanking.model.oidc.AccessTokenResponse) PairClientIDAuthMethod(com.forgerock.openbanking.aspsp.as.service.PairClientIDAuthMethod) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

AMGateway (com.forgerock.openbanking.am.gateway.AMGateway)3 AccessTokenReWriteException (com.forgerock.openbanking.common.error.exception.AccessTokenReWriteException)2 OBErrorResponseException (com.forgerock.openbanking.exceptions.OBErrorResponseException)2 SignedJWT (com.nimbusds.jwt.SignedJWT)2 ResponseEntity (org.springframework.http.ResponseEntity)2 PairClientIDAuthMethod (com.forgerock.openbanking.aspsp.as.service.PairClientIDAuthMethod)1 RedirectionAction (com.forgerock.openbanking.common.model.rcs.RedirectionAction)1 GrantType (com.forgerock.openbanking.constants.OIDCConstants.GrantType)1 OBErrorException (com.forgerock.openbanking.exceptions.OBErrorException)1 Tpp (com.forgerock.openbanking.model.Tpp)1 AccessTokenResponse (com.forgerock.openbanking.model.oidc.AccessTokenResponse)1 OIDCRegistrationResponse (com.forgerock.openbanking.model.oidc.OIDCRegistrationResponse)1 ParseException (java.text.ParseException)1 Test (org.junit.Test)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)1 HttpHeaders (org.springframework.http.HttpHeaders)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1