Search in sources :

Example 1 with AUTHORIZATION_CODE

use of org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE in project carbon-apimgt by wso2.

the class AbstractKeyManager method buildFromJSON.

/**
 * This method will accept json String and will do the json parse will set oAuth application properties to OAuthApplicationInfo object.
 *
 * @param jsonInput this jsonInput will contain set of oAuth application properties.
 * @return OAuthApplicationInfo object will be return.
 * @throws APIManagementException
 */
public OAuthApplicationInfo buildFromJSON(OAuthApplicationInfo oAuthApplicationInfo, String jsonInput) throws APIManagementException {
    // initiate json parser.
    JSONParser parser = new JSONParser();
    JSONObject jsonObject;
    try {
        // parse json String
        jsonObject = (JSONObject) parser.parse(jsonInput);
        if (jsonObject != null) {
            // create a map to hold json parsed objects.
            Map<String, Object> params = (Map) jsonObject;
            if (params.get(APIConstants.JSON_CALLBACK_URL) != null) {
                oAuthApplicationInfo.setCallBackURL((String) params.get(APIConstants.JSON_CALLBACK_URL));
            }
            if (params.get(APIConstants.JSON_GRANT_TYPES) != null) {
                String grantTypeString = params.get(APIConstants.JSON_GRANT_TYPES).toString();
                if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL()) && (grantTypeString.contains("implicit") || grantTypeString.contains("authorization_code"))) {
                    throw new EmptyCallbackURLForCodeGrantsException("The callback url must have at least one URI " + "value when using Authorization code or implicit grant types.");
                }
            }
            // set client Id
            if (params.get(APIConstants.JSON_CLIENT_ID) != null) {
                oAuthApplicationInfo.setClientId((String) params.get(APIConstants.JSON_CLIENT_ID));
            }
            // set client secret
            if (params.get(APIConstants.JSON_CLIENT_SECRET) != null) {
                oAuthApplicationInfo.setClientSecret((String) params.get(APIConstants.JSON_CLIENT_SECRET));
            }
            // copy all params map in to OAuthApplicationInfo's Map object.
            oAuthApplicationInfo.putAll(params);
            validateOAuthAppCreationProperties(oAuthApplicationInfo);
            return oAuthApplicationInfo;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) EmptyCallbackURLForCodeGrantsException(org.wso2.carbon.apimgt.api.EmptyCallbackURLForCodeGrantsException)

Example 2 with AUTHORIZATION_CODE

use of org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE 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 AUTHORIZATION_CODE

use of org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE in project identity-inbound-auth-oauth by wso2-extensions.

the class AuthorizationCodeDAOImpl method getAuthorizationCodeByCodeId.

private String getAuthorizationCodeByCodeId(String codeId) throws IdentityOAuth2Exception {
    if (log.isDebugEnabled()) {
        log.debug("Retrieving authorization code by code id: " + codeId);
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet resultSet = null;
    try {
        String sql = SQLQueries.RETRIEVE_AUTHZ_CODE_BY_CODE_ID;
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, codeId);
        resultSet = prepStmt.executeQuery();
        if (resultSet.next()) {
            return resultSet.getString("AUTHORIZATION_CODE");
        }
        return null;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while retrieving 'Authorization Code' for " + "authorization code : " + codeId;
        throw new IdentityOAuth2Exception(errorMsg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 4 with AUTHORIZATION_CODE

use of org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE in project identity-inbound-auth-oauth by wso2-extensions.

the class DefaultOIDCClaimsCallbackHandler method getCachedUserAttributes.

private Map<ClaimMapping, String> getCachedUserAttributes(OAuthTokenReqMessageContext requestMsgCtx) {
    Map<ClaimMapping, String> userAttributes = getUserAttributesCachedAgainstToken(getAccessToken(requestMsgCtx));
    if (log.isDebugEnabled()) {
        log.debug("Retrieving claims cached against access_token for user: " + requestMsgCtx.getAuthorizedUser());
    }
    if (isEmpty(userAttributes)) {
        if (log.isDebugEnabled()) {
            log.debug("No claims cached against the access_token for user: " + requestMsgCtx.getAuthorizedUser() + ". Retrieving claims cached against the authorization code.");
        }
        userAttributes = getUserAttributesCachedAgainstAuthorizationCode(getAuthorizationCode(requestMsgCtx));
        if (log.isDebugEnabled()) {
            log.debug("Retrieving claims cached against authorization_code for user: " + requestMsgCtx.getAuthorizedUser());
        }
    }
    /* When building the jwt token, we cannot add it to authorization cache, as we save entries against, access
         token. Hence if it is added against authenticated user object.*/
    if (isEmpty(userAttributes)) {
        if (log.isDebugEnabled()) {
            log.debug("No claims found in authorization cache. Retrieving claims from attributes of user : " + requestMsgCtx.getAuthorizedUser());
        }
        AuthenticatedUser user = requestMsgCtx.getAuthorizedUser();
        userAttributes = user != null ? user.getUserAttributes() : null;
    }
    // In the refresh flow, we need to follow the same way to get the claims.
    if (isEmpty(userAttributes)) {
        if (log.isDebugEnabled()) {
            log.debug("No claims found in user in user attributes for user : " + requestMsgCtx.getAuthorizedUser());
        }
        Object previousAccessTokenObject = requestMsgCtx.getProperty(RefreshGrantHandler.PREV_ACCESS_TOKEN);
        if (previousAccessTokenObject != null) {
            if (log.isDebugEnabled()) {
                log.debug("Retrieving claims from previous access token of user : " + requestMsgCtx.getAuthorizedUser());
            }
            RefreshTokenValidationDataDO refreshTokenValidationDataDO = (RefreshTokenValidationDataDO) previousAccessTokenObject;
            userAttributes = getUserAttributesCachedAgainstToken(refreshTokenValidationDataDO.getAccessToken());
            requestMsgCtx.addProperty(OIDCConstants.HAS_NON_OIDC_CLAIMS, isTokenHasCustomUserClaims(refreshTokenValidationDataDO));
        }
    }
    return userAttributes;
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) RefreshTokenValidationDataDO(org.wso2.carbon.identity.oauth2.model.RefreshTokenValidationDataDO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 5 with AUTHORIZATION_CODE

use of org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE in project product-is by wso2.

the class AbstractAdaptiveAuthenticationTestCase method createOauthApp.

protected void createOauthApp(String callback, String appName, OauthAdminClient oAuthAdminClient) throws RemoteException, OAuthAdminServiceIdentityOAuthAdminException {
    OAuthConsumerAppDTO appDTO = new OAuthConsumerAppDTO();
    appDTO.setCallbackUrl(callback);
    appDTO.setGrantTypes("authorization_code implicit password client_credentials refresh_token " + "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
    appDTO.setOAuthVersion(OAuth2Constant.OAUTH_VERSION_2);
    appDTO.setApplicationName(appName);
    oAuthAdminClient.registerOAuthApplicationData(appDTO);
    OAuthConsumerAppDTO[] appDtos = oAuthAdminClient.getAllOAuthApplicationData();
    for (OAuthConsumerAppDTO appDto : appDtos) {
        if (appDto.getApplicationName().equals(appName)) {
            consumerKey = appDto.getOauthConsumerKey();
            consumerSecret = appDto.getOauthConsumerSecret();
        }
    }
}
Also used : OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO)

Aggregations

OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO)14 Test (org.testng.annotations.Test)5 ArrayList (java.util.ArrayList)4 Matchers.anyString (org.mockito.Matchers.anyString)3 HashMap (java.util.HashMap)2 HttpResponse (org.apache.http.HttpResponse)2 JSONObject (org.json.simple.JSONObject)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 BeforeClass (org.testng.annotations.BeforeClass)2 Claim (org.wso2.carbon.identity.application.common.model.xsd.Claim)2 ClaimConfig (org.wso2.carbon.identity.application.common.model.xsd.ClaimConfig)2 ClaimMapping (org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping)2 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig)2 OutboundProvisioningConfig (org.wso2.carbon.identity.application.common.model.xsd.OutboundProvisioningConfig)2 Property (org.wso2.carbon.identity.application.common.model.xsd.Property)2 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)2 JsonObject (com.google.gson.JsonObject)1 Secret (com.nimbusds.oauth2.sdk.auth.Secret)1 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)1 Method (java.lang.reflect.Method)1