Search in sources :

Example 1 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO 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 OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO 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 OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpoint method handleErrorResponse.

private Response handleErrorResponse(OAuth2AccessTokenRespDTO oauth2AccessTokenResp) throws OAuthSystemException {
    // if there is an auth failure, HTTP 401 Status Code should be sent back to the client.
    if (OAuth2ErrorCodes.INVALID_CLIENT.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleBasicAuthFailure(oauth2AccessTokenResp.getErrorMsg());
    } else if (SQL_ERROR.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleSQLError();
    } else if (OAuth2ErrorCodes.SERVER_ERROR.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleServerError();
    } else {
        // Otherwise send back HTTP 400 Status Code
        OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(oauth2AccessTokenResp.getErrorCode()).setErrorDescription(oauth2AccessTokenResp.getErrorMsg()).buildJSONMessage();
        ResponseHeader[] headers = oauth2AccessTokenResp.getResponseHeaders();
        ResponseBuilder respBuilder = Response.status(response.getResponseStatus());
        if (headers != null) {
            for (ResponseHeader header : headers) {
                if (header != null) {
                    respBuilder.header(header.getKey(), header.getValue());
                }
            }
        }
        return respBuilder.entity(response.getBody()).build();
    }
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) OAuthTokenResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 4 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class CibaGrantHandler method issue.

@Override
public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    OAuth2AccessTokenRespDTO responseDTO = super.issue(tokReqMsgCtx);
    String authReqId = getAuthReqId(tokReqMsgCtx);
    CibaAuthCodeDO cibaAuthCodeDO = retrieveCibaAuthCode(authReqId);
    try {
        CibaDAOFactory.getInstance().getCibaAuthMgtDAO().updateStatus(cibaAuthCodeDO.getCibaAuthCodeKey(), AuthReqStatus.TOKEN_ISSUED);
        if (log.isDebugEnabled()) {
            log.debug("Successfully updated the status of authentication request made by client:" + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId());
        }
    } catch (CibaCoreException e) {
        throw new IdentityOAuth2Exception("Error occurred in persisting status for the request made with " + "auth_req_id: " + authReqId, e);
    }
    return responseDTO;
}
Also used : OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) CibaAuthCodeDO(org.wso2.carbon.identity.oauth.ciba.model.CibaAuthCodeDO) CibaCoreException(org.wso2.carbon.identity.oauth.ciba.exceptions.CibaCoreException)

Example 5 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class RefreshGrantHandler method issue.

@Override
public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    OAuth2AccessTokenReqDTO tokenReq = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    // An active or expired token will be returned. Since we do the validation for active or expired token in
    // validateGrant() no need to do it here again also no need to read it from DB again. Simply get it from
    // context property.
    RefreshTokenValidationDataDO validationBean = (RefreshTokenValidationDataDO) tokReqMsgCtx.getProperty(PREV_ACCESS_TOKEN);
    if (isRefreshTokenExpired(validationBean)) {
        return handleError(OAuth2ErrorCodes.INVALID_GRANT, "Refresh token is expired.", tokenReq);
    }
    AccessTokenDO accessTokenBean = createAccessTokenBean(tokReqMsgCtx, tokenReq, validationBean);
    persistNewToken(tokReqMsgCtx, accessTokenBean, tokenReq.getClientId());
    if (log.isDebugEnabled()) {
        log.debug("Persisted an access token for the refresh token, " + "Client ID : " + tokenReq.getClientId() + ", Authorized user : " + tokReqMsgCtx.getAuthorizedUser() + ", Timestamp : " + accessTokenBean.getIssuedTime() + ", Validity period (s) : " + accessTokenBean.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(tokReqMsgCtx.getScope()) + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + getTokenType());
    }
    setTokenDataToMessageContext(tokReqMsgCtx, accessTokenBean);
    addUserAttributesToCache(accessTokenBean, tokReqMsgCtx);
    return buildTokenResponse(tokReqMsgCtx, accessTokenBean);
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)

Aggregations

OAuth2AccessTokenRespDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO)30 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)19 Test (org.testng.annotations.Test)18 HashMap (java.util.HashMap)16 Matchers.anyString (org.mockito.Matchers.anyString)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)12 OAuthClientAuthnContext (org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)10 AuthorizationGrantHandler (org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler)10 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 ArrayList (java.util.ArrayList)7 ResponseHeader (org.wso2.carbon.identity.oauth2.ResponseHeader)6 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)5 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)5 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)5 Hashtable (java.util.Hashtable)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 Date (java.util.Date)3 Map (java.util.Map)3