Search in sources :

Example 1 with InvalidRequestParentException

use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthRevocationEndpointTest method testRevokeAccessToken.

@Test(dataProvider = "testRevokeAccessTokenDataProvider")
public void testRevokeAccessToken(String authzHeader, boolean addReqParams, String token, String tokenHint, String callback, String clientId, String secret, String respError, Object headerObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
    MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>();
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    parameterMap.add(TOKEN_PARAM, token);
    parameterMap.add(TOKEN_TYPE_HINT_PARAM, tokenHint);
    parameterMap.add(CALLBACK_PARAM, callback);
    Map<String, String[]> requestedParams = new HashMap<>();
    if (addReqParams) {
        requestedParams.put(TOKEN_PARAM, new String[] { "" });
        requestedParams.put(TOKEN_TYPE_HINT_PARAM, new String[] { "" });
        requestedParams.put(CALLBACK_PARAM, new String[] { "" });
    }
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    HttpServletRequest request = mockHttpRequest(requestedParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
    spy(EndpointUtil.class);
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    final OAuthRevocationRequestDTO[] revokeReqDTO;
    revokeReqDTO = new OAuthRevocationRequestDTO[1];
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            revokeReqDTO[0] = (OAuthRevocationRequestDTO) invocation.getArguments()[0];
            return oAuthRevocationResponseDTO;
        }
    }).when(oAuth2Service).revokeTokenByOAuthClient(any(OAuthRevocationRequestDTO.class));
    when(oAuthRevocationResponseDTO.getErrorCode()).thenReturn(respError);
    when(oAuthRevocationResponseDTO.getErrorMsg()).thenReturn(respError);
    when(oAuthRevocationResponseDTO.getResponseHeaders()).thenReturn(responseHeaders);
    Response response;
    try {
        response = revocationEndpoint.revokeAccessToken(request, parameterMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    if (expectedErrorCode != null) {
        assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
        if (StringUtils.isNotEmpty(callback)) {
            assertTrue(response.getEntity().toString().contains(callback), "Callback is not added to the response");
        }
    }
}
Also used : OAuthRevocationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO) ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Matchers.anyString(org.mockito.Matchers.anyString) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 2 with InvalidRequestParentException

use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testIssueAccessToken.

@Test(dataProvider = "testIssueAccessTokenDataProvider", groups = "testWithConnection")
public void testIssueAccessToken(String clientId, String authzHeader, Object paramMapObj, String grantType, String idToken, Object headerObj, Object customResponseParamObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
    MultivaluedMap<String, String> paramMap = (MultivaluedMap<String, String>) paramMapObj;
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    Map<String, String> customResponseParameters = (Map<String, String>) customResponseParamObj;
    Map<String, String[]> requestParams = new HashMap<>();
    if (clientId != null) {
        requestParams.put(OAuth.OAUTH_CLIENT_ID, clientId.split(","));
    }
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
    requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
    requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {

        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));
    spy(EndpointUtil.class);
    doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn(oAuth2AccessTokenRespDTO);
    when(oAuth2AccessTokenRespDTO.getAccessToken()).thenReturn(ACCESS_TOKEN);
    when(oAuth2AccessTokenRespDTO.getRefreshToken()).thenReturn(REFRESH_TOKEN);
    when(oAuth2AccessTokenRespDTO.getExpiresIn()).thenReturn(3600L);
    when(oAuth2AccessTokenRespDTO.getAuthorizedScopes()).thenReturn("scope1");
    when(oAuth2AccessTokenRespDTO.getIDToken()).thenReturn(idToken);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
    when(oAuth2AccessTokenRespDTO.getParameters()).thenReturn(customResponseParameters);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    Response response;
    try {
        response = oAuth2TokenEndpoint.issueAccessToken(request, paramMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    final String responseBody = response.getEntity().toString();
    if (customResponseParameters != null) {
        customResponseParameters.forEach((key, value) -> assertTrue(responseBody.contains(key) && responseBody.contains(value), "Expected custom response parameter: " + key + " not found in token response."));
    }
    if (expectedErrorCode != null) {
        assertTrue(responseBody.contains(expectedErrorCode), "Expected error code not found");
    } else if (HttpServletResponse.SC_OK == expectedStatus) {
        assertTrue(responseBody.contains(ACCESS_TOKEN), "Successful response should contain access token");
    }
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with InvalidRequestParentException

use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testAuthorizePost.

@Test(dataProvider = "providePostParams")
public void testAuthorizePost(Object paramObject, Map<String, String[]> requestParams, int expected) throws Exception {
    MultivaluedMap<String, String> paramMap = (MultivaluedMap<String, String>) paramObject;
    when(httpServletRequest.getParameterMap()).thenReturn(requestParams);
    when(httpServletRequest.getParameterNames()).thenReturn(new Vector(requestParams.keySet()).elements());
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    mockOAuthServerConfiguration();
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorizePost(httpServletRequest, httpServletResponse, paramMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertEquals(response.getStatus(), expected, "Unexpected HTTP response status");
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) Matchers.anyString(org.mockito.Matchers.anyString) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Vector(java.util.Vector) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with InvalidRequestParentException

use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testIdentityOAuthAdminException.

@Test(dependsOnGroups = "testWithConnection")
public void testIdentityOAuthAdminException() throws Exception {
    // OAuthAdminException will not occur due to introduce a new Service to get the App State instead directly use
    // dao
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    // Closing connection to create SQLException
    connection.close();
    mockEndpointUtil(false);
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND);
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with InvalidRequestParentException

use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.

/**
 * This method use to call authentication framework directly via API other than using HTTP redirects.
 * Sending wrapper request object to doGet method since other original request doesn't exist required parameters
 * Doesn't check SUCCESS_COMPLETED since taking decision with INCOMPLETE status
 *
 * @param type authenticator type
 * @throws URISyntaxException
 * @throws InvalidRequestParentException
 * @Param type OAuthMessage
 */
private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage, String type) throws URISyntaxException, InvalidRequestParentException {
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", oAuthMessage.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Forward authorization request to framework for user authentication.", "hand-over-to-framework", null);
    }
    try {
        String sessionDataKey = (String) oAuthMessage.getRequest().getAttribute(FrameworkConstants.SESSION_DATA_KEY);
        CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
        CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(oAuthMessage.getRequest());
        requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
        requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
        CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
        commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
        Object attribute = oAuthMessage.getRequest().getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
        if (attribute != null) {
            if (attribute == AuthenticatorFlowStatus.INCOMPLETE) {
                if (responseWrapper.isRedirect()) {
                    return Response.status(HttpServletResponse.SC_FOUND).location(buildURI(responseWrapper.getRedirectURL())).build();
                } else {
                    return Response.status(HttpServletResponse.SC_OK).entity(responseWrapper.getContent()).build();
                }
            } else {
                return authorize(requestWrapper, responseWrapper);
            }
        } else {
            requestWrapper.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.UNKNOWN);
            return authorize(requestWrapper, responseWrapper);
        }
    } catch (ServletException | IOException | URLBuilderException e) {
        log.error("Error occurred while sending request to authentication framework.");
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oAuthMessage.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "hand-over-to-framework", null);
        }
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Aggregations

HashMap (java.util.HashMap)14 InvalidRequestParentException (org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException)13 HttpServletResponse (javax.servlet.http.HttpServletResponse)12 Response (javax.ws.rs.core.Response)12 Matchers.anyString (org.mockito.Matchers.anyString)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 BeforeTest (org.testng.annotations.BeforeTest)12 Test (org.testng.annotations.Test)12 InvalidRequestExceptionMapper (org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper)12 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)11 AfterTest (org.testng.annotations.AfterTest)11 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)9 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)9 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)9 OAuth2Util (org.wso2.carbon.identity.oauth2.util.OAuth2Util)7 IOException (java.io.IOException)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 SessionDataCacheKey (org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)5 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4