Search in sources :

Example 1 with RedirectionAction

use of com.forgerock.openbanking.common.model.rcs.RedirectionAction 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 RedirectionAction

use of com.forgerock.openbanking.common.model.rcs.RedirectionAction in project openbanking-aspsp by OpenBankingToolkit.

the class RCSConsentDecisionApiControllerTest method decisionAccountSharing.

@Test
public void decisionAccountSharing() throws OBErrorException, JsonProcessingException {
    // Given
    String signedJwtEncoded = toEncodedSignedTestJwt("jwt/singlePaymentConsentRequestPayload.json");
    String ssoToken = "dlkjdsflkjdlsfhlkfdk";
    ConsentDecision consentDecision = new ConsentDecision();
    consentDecision.setDecision(RCSConstants.Decision.ALLOW);
    consentDecision.setConsentJwt(signedJwtEncoded);
    String consentDecisionSerialized = objectMapper.writeValueAsString(consentDecision);
    // When
    ResponseEntity responseEntity = consentDecisionApiController.decision(consentDecisionSerialized, ssoToken);
    // Then
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(responseEntity.getBody()).isNotNull();
    ObjectMapper objectMapper = new ObjectMapper();
    RedirectionAction redirectAction = (RedirectionAction) responseEntity.getBody();
    assertThat(redirectAction).isNotNull();
    assertThat(redirectAction.getRedirectUri()).contains("re-writtenIdToken");
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) RedirectionAction(com.forgerock.openbanking.common.model.rcs.RedirectionAction) ConsentDecision(com.forgerock.openbanking.common.model.rcs.consentdecision.ConsentDecision) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 3 with RedirectionAction

use of com.forgerock.openbanking.common.model.rcs.RedirectionAction in project openbanking-aspsp by OpenBankingToolkit.

the class HeadLessAuthorisationService method getAuthorisation.

public ResponseEntity getAuthorisation(AMGateway amGateway, String responseType, String clientId, String state, String nonce, String scopes, String redirectUri, String requestParameters, String username, String password) throws OBErrorResponseException {
    log.debug("Start the headless authorisation flow.");
    log.debug("The X_HEADLESS_AUTH_* received are: username='{}' and password='{}'", username, password);
    if (username == null || username.equals("")) {
        username = headLessAuthProperties.getDefaultPsu().getUsername();
    }
    if (password == null || password.equals("")) {
        password = headLessAuthProperties.getDefaultPsu().getPassword();
    }
    try {
        log.debug("Login to AM using the user username='{}' and password='{}'", username, password);
        AMAuthentication.TokenResponse authenticate = amAuthentication.authenticate(username, password, "simple%20login");
        log.debug("Successfully authenticated. The token id : '{}'", authenticate.getTokenId());
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(amRoot).path("/oauth2/authorize").queryParam("response_type", responseType).queryParam("client_id", clientId).queryParam("state", state).queryParam("nonce", nonce).queryParam("scope", scopes).queryParam("redirect_uri", redirectUri).queryParam("request", requestParameters);
        log.debug("Call the AM authorisation endpoint to get the consent request JWT");
        String consentRequest = getConsentRequest(amGateway, uriComponentsBuilder.toUriString(), authenticate);
        log.debug("Call the RCS with the consent request '{}'", consentRequest);
        RedirectionAction redirectionAction = getRedirectionActionFromRCS(authenticate, consentRequest);
        log.debug("The redirection action received from the RCS: '{}'", redirectionAction);
        return ResponseEntity.status(HttpStatus.FOUND).header("Location", redirectionAction.getRedirectUri()).build();
    } catch (WrongResponseEntity e) {
        return e.responseEntity;
    }
}
Also used : AMAuthentication(com.forgerock.openbanking.am.services.AMAuthentication) RedirectionAction(com.forgerock.openbanking.common.model.rcs.RedirectionAction) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder)

Example 4 with RedirectionAction

use of com.forgerock.openbanking.common.model.rcs.RedirectionAction in project openbanking-aspsp by OpenBankingToolkit.

the class AuthorisationApiControllerTest method shouldReturnRedirectActionWhenResponseTypeNotMatch.

@Test
public void shouldReturnRedirectActionWhenResponseTypeNotMatch() throws OBErrorException, OBErrorResponseException {
    // Given
    List<String> responseTypes = List.of("code id_token");
    given(discoveryConfig.getSupportedResponseTypes()).willReturn(responseTypes);
    String jwt = toEncodedSignedTestJwt("jwt/authorisation.jwt");
    OIDCRegistrationResponse registrationResponse = new OIDCRegistrationResponse();
    registrationResponse.setJwks_uri("url");
    Tpp tpp = new Tpp();
    tpp.setRegistrationResponse(registrationResponse);
    // When
    ResponseEntity<RedirectionAction> responseEntity = authorisationApiController.getAuthorisation("responseTypes.get(0)", "98e119f6-196f-4296-98d4-f1a2f445bca2", "98e119f6-xxxx-yyyy-zzzz-f1a2f445bca2", null, "openid accounts", "https://www.google.com", jwt, true, null, null, null, null, null);
    // Then
    assertThat(responseEntity).isNotNull();
    assertThat(responseEntity.getHeaders().getLocation()).isNotNull();
    assertTrue(responseEntity.getHeaders().getLocation().toString().contains("error"));
}
Also used : RedirectionAction(com.forgerock.openbanking.common.model.rcs.RedirectionAction) Tpp(com.forgerock.openbanking.model.Tpp) OIDCRegistrationResponse(com.forgerock.openbanking.model.oidc.OIDCRegistrationResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 5 with RedirectionAction

use of com.forgerock.openbanking.common.model.rcs.RedirectionAction in project openbanking-aspsp by OpenBankingToolkit.

the class RCSCustomerInfoDetailsApiTest method shouldReturnRedirectActionWhenCustomerInfoNotFound.

@Test
public void shouldReturnRedirectActionWhenCustomerInfoNotFound() throws OBErrorException {
    FRAccountAccessConsent frAccountAccessConsent = JMockData.mock(FRAccountAccessConsent.class);
    frAccountAccessConsent.setConsentId(IntentType.CUSTOMER_INFO_CONSENT.generateIntentId());
    frAccountAccessConsent.setCustomerInfo(null);
    given(tppStoreService.findById(frAccountAccessConsent.getAispId())).willReturn(Optional.of(Tpp.builder().clientId(frAccountAccessConsent.getClientId()).build()));
    given(accountRequestStoreService.get(any())).willReturn(Optional.ofNullable(frAccountAccessConsent));
    given(customerInfoRepository.findByUserID(any())).willReturn(null);
    given(rcsErrorService.invalidConsentError(any(), any())).willReturn(ResponseEntity.ok(RedirectionAction.builder().redirectUri("redirect_uri_value").build()));
    ResponseEntity<RedirectionAction> response = api.consentDetails("asdfasdc", Collections.EMPTY_LIST, frAccountAccessConsent.getUserId(), frAccountAccessConsent.getConsentId(), frAccountAccessConsent.getClientId());
    RedirectionAction redirectionAction = response.getBody();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(redirectionAction.getRedirectUri()).isNotNull();
}
Also used : FRAccountAccessConsent(com.forgerock.openbanking.common.model.openbanking.persistence.account.FRAccountAccessConsent) RedirectionAction(com.forgerock.openbanking.common.model.rcs.RedirectionAction) Test(org.junit.Test)

Aggregations

RedirectionAction (com.forgerock.openbanking.common.model.rcs.RedirectionAction)6 Test (org.junit.Test)4 OBErrorException (com.forgerock.openbanking.exceptions.OBErrorException)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 ResponseEntity (org.springframework.http.ResponseEntity)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 AMGateway (com.forgerock.openbanking.am.gateway.AMGateway)1 AMAuthentication (com.forgerock.openbanking.am.services.AMAuthentication)1 AccessTokenReWriteException (com.forgerock.openbanking.common.error.exception.AccessTokenReWriteException)1 FRAccountAccessConsent (com.forgerock.openbanking.common.model.openbanking.persistence.account.FRAccountAccessConsent)1 ConsentDecision (com.forgerock.openbanking.common.model.rcs.consentdecision.ConsentDecision)1 OBErrorResponseException (com.forgerock.openbanking.exceptions.OBErrorResponseException)1 Tpp (com.forgerock.openbanking.model.Tpp)1 OIDCRegistrationResponse (com.forgerock.openbanking.model.oidc.OIDCRegistrationResponse)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ParseException (java.text.ParseException)1 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)1 HttpHeaders (org.springframework.http.HttpHeaders)1 UriComponents (org.springframework.web.util.UriComponents)1 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)1