Search in sources :

Example 1 with OAuthValidator

use of org.apache.oltu.oauth2.common.validators.OAuthValidator 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 2 with OAuthValidator

use of org.apache.oltu.oauth2.common.validators.OAuthValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testGetAccessToken.

@Test(dataProvider = "testGetAccessTokenDataProvider")
public void testGetAccessToken(String grantType, String additionalParameters) throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(OAuth.OAUTH_CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
    requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
    // Required params for authorization_code grant type
    requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_CODE, new String[] { "auth_code" });
    // Required params for password grant type
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
    // Required params for refresh token grant type
    requestParams.put(OAuth.OAUTH_REFRESH_TOKEN, new String[] { REFRESH_TOKEN });
    // Required params for saml2 bearer grant type
    requestParams.put(OAuth.OAUTH_ASSERTION, new String[] { "dummyAssertion" });
    // Required params for IWA_NLTM grant type
    requestParams.put(OAuthConstants.WINDOWS_TOKEN, new String[] { "dummyWindowsToken" });
    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {

        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
    grantTypeValidators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
    grantTypeValidators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class);
    grantTypeValidators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
    grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString(), NTLMAuthenticationValidator.class);
    grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString(), SAML2GrantValidator.class);
    mockOAuthServerConfiguration();
    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    spy(EndpointUtil.class);
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    final Map<String, String> parametersSetToRequest = new HashMap<>();
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            OAuth2AccessTokenReqDTO request = (OAuth2AccessTokenReqDTO) invocation.getArguments()[0];
            parametersSetToRequest.put(OAuth.OAUTH_CODE, request.getAuthorizationCode());
            parametersSetToRequest.put(OAuth.OAUTH_USERNAME, request.getResourceOwnerUsername());
            parametersSetToRequest.put(OAuth.OAUTH_PASSWORD, request.getResourceOwnerPassword());
            parametersSetToRequest.put(OAuth.OAUTH_REFRESH_TOKEN, request.getRefreshToken());
            parametersSetToRequest.put(OAuth.OAUTH_ASSERTION, request.getAssertion());
            parametersSetToRequest.put(OAuthConstants.WINDOWS_TOKEN, request.getWindowsToken());
            parametersSetToRequest.put(OAuth.OAUTH_GRANT_TYPE, request.getGrantType());
            OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO();
            return tokenRespDTO;
        }
    }).when(oAuth2Service).issueAccessToken(any(OAuth2AccessTokenReqDTO.class));
    CarbonOAuthTokenRequest oauthRequest = new CarbonOAuthTokenRequest(request);
    HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(request);
    Class<?> clazz = OAuth2TokenEndpoint.class;
    Object tokenEndpointObj = clazz.newInstance();
    Method getAccessToken = tokenEndpointObj.getClass().getDeclaredMethod("issueAccessToken", CarbonOAuthTokenRequest.class, HttpServletRequestWrapper.class);
    getAccessToken.setAccessible(true);
    OAuth2AccessTokenRespDTO tokenRespDTO = (OAuth2AccessTokenRespDTO) getAccessToken.invoke(tokenEndpointObj, oauthRequest, httpServletRequestWrapper);
    assertNotNull(tokenRespDTO, "ResponseDTO is null");
    String[] paramsToCheck = additionalParameters.split(",");
    for (String param : paramsToCheck) {
        assertNotNull(parametersSetToRequest.get(param), "Required parameter " + param + " is not set for " + grantType + "grant type");
    }
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) Method(java.lang.reflect.Method) HttpMethod(javax.ws.rs.HttpMethod) CarbonOAuthTokenRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthTokenRequest) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) InvocationOnMock(org.mockito.invocation.InvocationOnMock) 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 OAuthValidator

use of org.apache.oltu.oauth2.common.validators.OAuthValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest1.

@Test(dataProvider = "provideHandleOAuthAuthorizationRequest1Data", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object spObj, String savedDisplayName) throws Exception {
    ServiceProvider sp = (ServiceProvider) spObj;
    sp.setApplicationName(APP_NAME);
    mockApplicationManagementService(sp);
    mockOAuthServerConfiguration();
    mockEndpointUtil(false);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(true);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
    when(oAuthServerConfiguration.isShowDisplayNameInConsentPage()).thenReturn(showDisplayName);
    Method handleOAuthAuthorizationRequest = authzEndpointObject.getClass().getDeclaredMethod("handleOAuthAuthorizationRequest", OAuthMessage.class);
    handleOAuthAuthorizationRequest.setAccessible(true);
    SessionDataCache sessionDataCache = mock(SessionDataCache.class);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    final SessionDataCacheEntry[] cacheEntry = new SessionDataCacheEntry[1];
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) {
            cacheEntry[0] = (SessionDataCacheEntry) invocation.getArguments()[1];
            return null;
        }
    }).when(sessionDataCache).addToCache(any(SessionDataCacheKey.class), any(SessionDataCacheEntry.class));
    when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
    when(oAuthMessage.getClientId()).thenReturn(CLIENT_ID_VALUE);
    handleOAuthAuthorizationRequest.invoke(authzEndpointObject, oAuthMessage);
    assertNotNull(cacheEntry[0], "Parameters not saved in cache");
    assertEquals(cacheEntry[0].getoAuth2Parameters().getDisplayName(), savedDisplayName);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) 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 OAuthValidator

use of org.apache.oltu.oauth2.common.validators.OAuthValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest.

/**
 * Tests the scenario of authorization request from the client
 */
@Test(dataProvider = "provideAuthzRequestData", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest(String clientId, String redirectUri, String pkceChallengeCode, String pkceChallengeMethod, String prompt, boolean clientValid, boolean pkceEnabled, boolean supportPlainPkce, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { clientId });
    // No consent data is saved in the cache yet and client doesn't send cache key
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { null });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE, new String[] { pkceChallengeCode });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD, new String[] { pkceChallengeMethod });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    if (redirectUri != null) {
        requestParams.put("acr_values", new String[] { redirectUri });
        requestParams.put("claims", new String[] { "essentialClaims" });
        requestParams.put(MultitenantConstants.TENANT_DOMAIN, new String[] { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME });
    }
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    // No authentication data is saved in the cache yet and client doesn't send cache key
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, null);
    if (prompt != null) {
        requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { prompt });
    }
    boolean checkErrorCode = ERROR_PAGE_URL.equals(expectedLocation);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockOAuthServerConfiguration();
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
    spy(FrameworkUtils.class);
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockEndpointUtil(false);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    when(oAuth2Service.isPKCESupportEnabled()).thenReturn(pkceEnabled);
    if (ERROR_PAGE_URL.equals(expectedLocation) && OAuthConstants.Prompt.NONE.equals(prompt)) {
        doThrow(new IdentityOAuth2Exception("error")).when(EndpointUtil.class, "getLoginPageURL", anyString(), anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap(), any());
        checkErrorCode = false;
    }
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(clientValid);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    if (!clientValid) {
        validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        validationResponseDTO.setErrorMsg("client is invalid");
    }
    validationResponseDTO.setPkceMandatory(supportPlainPkce);
    validationResponseDTO.setPkceSupportPlain(supportPlainPkce);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    if (StringUtils.equals(expectedLocation, LOGIN_PAGE_URL) || StringUtils.equals(expectedLocation, ERROR_PAGE_URL)) {
        CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
        doAnswer(invocation -> {
            CommonAuthRequestWrapper request = (CommonAuthRequestWrapper) invocation.getArguments()[0];
            request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
            CommonAuthResponseWrapper wrapper = (CommonAuthResponseWrapper) invocation.getArguments()[1];
            wrapper.sendRedirect(expectedLocation);
            return null;
        }).when(handler).doGet(any(), any());
        whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
    }
    mockServiceURLBuilder();
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response);
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
    MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
    assertNotNull(responseMetadata, "Response metadata is null");
    assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
    String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
    assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
    if (checkErrorCode) {
        assertTrue(location.contains(OAuth2ErrorCodes.INVALID_REQUEST), "Expected error code not found in URL");
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) 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) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) 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 OAuthValidator

use of org.apache.oltu.oauth2.common.validators.OAuthValidator in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testTokenErrorResponse.

@Test(dataProvider = "testTokenErrorResponseDataProvider", groups = "testWithConnection")
public void testTokenErrorResponse(String errorCode, Object headerObj, int expectedStatus, String expectedErrorCode) throws Exception {
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { GrantType.PASSWORD.toString() });
    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(AUTHORIZATION_HEADER);
    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.getErrorMsg()).thenReturn("Token Response error");
    when(oAuth2AccessTokenRespDTO.getErrorCode()).thenReturn(errorCode);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
    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, new MultivaluedHashMap<String, String>());
    } 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");
    assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
}
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) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) 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) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

HashMap (java.util.HashMap)5 Hashtable (java.util.Hashtable)5 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)5 OAuthValidator (org.apache.oltu.oauth2.common.validators.OAuthValidator)5 Matchers.anyString (org.mockito.Matchers.anyString)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 AfterTest (org.testng.annotations.AfterTest)5 BeforeTest (org.testng.annotations.BeforeTest)5 Test (org.testng.annotations.Test)5 ArrayList (java.util.ArrayList)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Response (javax.ws.rs.core.Response)3 InvalidRequestParentException (org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException)3 InvalidRequestExceptionMapper (org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper)3 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)3 Method (java.lang.reflect.Method)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 HttpMethod (javax.ws.rs.HttpMethod)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2