Search in sources :

Example 26 with AuthzCodeDO

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

the class TenantCreationEventListener method revokeTokens.

private void revokeTokens(int tenantId) throws StratosException {
    try {
        Set<AccessTokenDO> accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokensByTenant(tenantId);
        Map<String, AccessTokenDO> latestAccessTokens = new HashMap<>();
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            String keyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser() + ":" + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + ":" + accessTokenDO.getAuthzUser().getFederatedIdPName();
            AccessTokenDO accessTokenDOFromMap = latestAccessTokens.get(keyString);
            if (accessTokenDOFromMap != null) {
                if (accessTokenDOFromMap.getIssuedTime().before(accessTokenDO.getIssuedTime())) {
                    latestAccessTokens.put(keyString, accessTokenDO);
                }
            } else {
                latestAccessTokens.put(keyString, accessTokenDO);
            }
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(), OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO);
        }
        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(latestAccessTokens.values().stream().map(AccessTokenDO::getAccessToken).toArray(String[]::new), OAuth2Util.isHashEnabled());
        List<AuthzCodeDO> latestAuthzCodes = OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().getLatestAuthorizationCodesByTenant(tenantId);
        // Remove the authorization code from the cache.
        latestAuthzCodes.stream().map(authzCodeDO -> authzCodeDO.getConsumerKey() + ":" + authzCodeDO.getAuthorizationCode()).forEach(OAuthUtil::clearOAuthCache);
        OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().deactivateAuthorizationCodes(latestAuthzCodes);
    } catch (IdentityOAuth2Exception e) {
        throw new StratosException("Error occurred while revoking Access Token of tenant: " + tenantId, e);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) StratosException(org.wso2.carbon.stratos.common.exception.StratosException) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) TenantMgtListener(org.wso2.carbon.stratos.common.listeners.TenantMgtListener) Set(java.util.Set) HashMap(java.util.HashMap) TenantInfoBean(org.wso2.carbon.stratos.common.beans.TenantInfoBean) List(java.util.List) IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) OAuthTokenPersistenceFactory(org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) Map(java.util.Map) OAuthUtil(org.wso2.carbon.identity.oauth.OAuthUtil) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2ServiceComponentHolder(org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) HashMap(java.util.HashMap) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) OAuthUtil(org.wso2.carbon.identity.oauth.OAuthUtil) StratosException(org.wso2.carbon.stratos.common.exception.StratosException)

Example 27 with AuthzCodeDO

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

the class AuthorizationCodeGrantHandler method validatePKCECode.

/**
 * Performs PKCE Validation for "Authorization Code" Grant Type
 *
 * @param authzCodeBean
 * @param verificationCode
 * @return true if PKCE is validated
 * @throws IdentityOAuth2Exception
 */
private boolean validatePKCECode(AuthzCodeDO authzCodeBean, String verificationCode) throws IdentityOAuth2Exception {
    String pkceCodeChallenge = authzCodeBean.getPkceCodeChallenge();
    String pkceCodeChallengeMethod = authzCodeBean.getPkceCodeChallengeMethod();
    OAuthAppDO oAuthApp = getOAuthAppDO(authzCodeBean.getConsumerKey());
    if (!validatePKCE(pkceCodeChallenge, verificationCode, pkceCodeChallengeMethod, oAuthApp)) {
        // possible malicious oAuthRequest
        log.warn("Failed PKCE Verification for oAuth 2.0 request");
        if (log.isDebugEnabled()) {
            log.debug("PKCE code verification failed for client : " + authzCodeBean.getConsumerKey());
        }
        throw new IdentityOAuth2Exception("PKCE validation failed");
    }
    return true;
}
Also used : OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)

Example 28 with AuthzCodeDO

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

the class AuthorizationCodeGrantHandler method deactivateAuthzCode.

private void deactivateAuthzCode(OAuthTokenReqMessageContext tokReqMsgCtx, String tokenId, String authzCode) throws IdentityOAuth2Exception {
    try {
        // Here we deactivate the authorization and in the process update the tokenId against the authorization
        // code so that we can correlate the current access token that is valid against the authorization code.
        AuthzCodeDO authzCodeDO = new AuthzCodeDO();
        authzCodeDO.setAuthorizationCode(authzCode);
        authzCodeDO.setOauthTokenId(tokenId);
        authzCodeDO.setAuthzCodeId(tokReqMsgCtx.getProperty(CODE_ID).toString());
        OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().deactivateAuthorizationCode(authzCodeDO);
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
            log.debug("Deactivated authorization code : " + authzCode);
        }
    } catch (IdentityException e) {
        throw new IdentityOAuth2Exception("Error occurred while deactivating authorization code", e);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 29 with AuthzCodeDO

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

the class AuthorizationCodeGrantHandler method validateGrant.

@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    super.validateGrant(tokReqMsgCtx);
    OAuth2AccessTokenReqDTO tokenReq = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    AuthzCodeDO authzCodeBean = getPersistedAuthzCode(tokenReq);
    validateAuthzCodeFromRequest(authzCodeBean, tokenReq.getClientId(), tokenReq.getAuthorizationCode());
    try {
        // If redirect_uri was given in the authorization request,
        // token request should send matching redirect_uri value.
        validateCallbackUrlFromRequest(tokenReq.getCallbackURI(), authzCodeBean.getCallbackUrl());
        validatePKCECode(authzCodeBean, tokenReq.getPkceCodeVerifier());
        setPropertiesForTokenGeneration(tokReqMsgCtx, tokenReq, authzCodeBean);
    } finally {
        // After validating grant, authorization code is revoked. This is done to stop repetitive usage of
        // same authorization code in erroneous token requests.
        tokReqMsgCtx.addProperty(CODE_ID, authzCodeBean.getAuthzCodeId());
        revokeAuthorizationCode(authzCodeBean);
    }
    if (log.isDebugEnabled()) {
        log.debug("Found Authorization Code for Client : " + tokenReq.getClientId() + ", authorized user : " + authzCodeBean.getAuthorizedUser() + ", scope : " + OAuth2Util.buildScopeString(authzCodeBean.getScope()));
    }
    return true;
}
Also used : AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)

Example 30 with AuthzCodeDO

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

the class AuthorizationCodeGrantHandlerTest method testValidateGrant.

@Test(dataProvider = "BuildTokenRequestMessageContext")
public void testValidateGrant(Object tokenRequestMessageContext, Object authzCode, boolean cacheEnabled, boolean debugEnabled, long timestamp, boolean expectedResult) throws Exception {
    AuthzCodeDO authzCodeDO = (AuthzCodeDO) authzCode;
    WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "cacheEnabled", cacheEnabled);
    OAuthCache oAuthCache = mock(OAuthCache.class);
    when(OAuthCache.getInstance()).thenReturn(oAuthCache);
    if (cacheEnabled) {
        WhiteboxImpl.setInternalState(authorizationCodeGrantHandler, "oauthCache", oAuthCache);
    }
    OAuthTokenReqMessageContext tokReqMsgCtx = (OAuthTokenReqMessageContext) tokenRequestMessageContext;
    oAuthServerConfiguration = mock(OAuthServerConfiguration.class);
    TokenPersistenceProcessor tokenPersistenceProcessor = mock(TokenPersistenceProcessor.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getPersistenceProcessor()).thenReturn(tokenPersistenceProcessor);
    OAuthAppDAO oAuthAppDAO = mock(OAuthAppDAO.class);
    OAuthAppDO oAuthAppDO = new OAuthAppDO();
    whenNew(OAuthAppDAO.class).withNoArguments().thenReturn(oAuthAppDAO);
    when(oAuthAppDAO.getAppInformation(anyString())).thenReturn(oAuthAppDO);
    AppInfoCache appInfoCache = mock(AppInfoCache.class);
    when(AppInfoCache.getInstance()).thenReturn(appInfoCache);
    doNothing().when(appInfoCache).addToCache(anyString(), any(OAuthAppDO.class));
    assertEquals(authorizationCodeGrantHandler.validateGrant(tokReqMsgCtx), expectedResult);
}
Also used : OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) AppInfoCache(org.wso2.carbon.identity.oauth.cache.AppInfoCache) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthCache(org.wso2.carbon.identity.oauth.cache.OAuthCache) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) TokenPersistenceProcessor(org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

AuthzCodeDO (org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)38 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)18 Test (org.testng.annotations.Test)11 Connection (java.sql.Connection)8 PreparedStatement (java.sql.PreparedStatement)8 SQLException (java.sql.SQLException)8 Timestamp (java.sql.Timestamp)8 Matchers.anyString (org.mockito.Matchers.anyString)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)8 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)8 ArrayList (java.util.ArrayList)7 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)6 ResultSet (java.sql.ResultSet)5 HashMap (java.util.HashMap)5 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)5 HashSet (java.util.HashSet)4 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)4 Map (java.util.Map)3 DataProvider (org.testng.annotations.DataProvider)3