Search in sources :

Example 41 with OAuth2Parameters

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

the class OAuth2AuthzEndpoint method handleApprovedAlwaysWithoutPromptingForNewConsent.

private String handleApprovedAlwaysWithoutPromptingForNewConsent(OAuthMessage oAuthMessage, OIDCSessionState sessionState, OAuth2Parameters oauth2Params) throws ConsentHandlingFailedException, OAuthSystemException, OAuthProblemException {
    AuthenticatedUser authenticatedUser = getLoggedInUser(oAuthMessage);
    String preConsent = handlePreConsentIncludingExistingConsents(oauth2Params, authenticatedUser);
    if (isConsentFromUserRequired(preConsent)) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oauth2Params.getClientId());
            params.put("prompt", oauth2Params.getPrompt());
            Map<String, Object> configs = new HashMap<>();
            configs.put("consentRequiredClaims", preConsent);
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "'prompt' is set to none, and existing user consent is incomplete for the OAuth client.", "validate-existing-consent", configs);
        }
        throw OAuthProblemException.error(OAuth2ErrorCodes.CONSENT_REQUIRED, "Consent approved always without prompting for new consent");
    } else {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oauth2Params.getClientId());
            params.put("prompt", oauth2Params.getPrompt());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "'prompt' is set to none, and existing user consent found for the OAuth client.", "validate-existing-consent", null);
        }
        return handleUserConsent(oAuthMessage, APPROVE, sessionState);
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 42 with OAuth2Parameters

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

the class OIDCRequestObjectUtilTest method testBuildRequestObjectTest.

@Test(dataProvider = "TestBuildRequestObjectTest")
public void testBuildRequestObjectTest(String requestObjectString, Map<String, Object> claims, boolean isSigned, boolean isEncrypted, boolean exceptionNotExpected, String errorMsg) throws Exception {
    OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
    oAuth2Parameters.setTenantDomain("carbon.super");
    oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
    OAuthAuthzRequest oAuthAuthzRequest = mock(OAuthAuthzRequest.class);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    when(oAuthAuthzRequest.getParam(Constants.REQUEST)).thenReturn(requestObjectString);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getTenantId("carbon.super")).thenReturn(-1234);
    when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
    when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate("wso2carbon"));
    OAuthAppDO oAuthAppDO = new OAuthAppDO();
    when(OAuth2Util.getAppInformationByClientId(TEST_CLIENT_ID_1)).thenReturn(oAuthAppDO);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    RequestObjectValidator requestObjectValidator = PowerMockito.spy(new RequestObjectValidatorImpl());
    when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
    PowerMockito.doReturn(SOME_SERVER_URL).when(requestObjectValidator, "getTokenEpURL", anyString());
    RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
    Map<String, RequestObjectBuilder> requestObjectBuilderMap = new HashMap<>();
    requestObjectBuilderMap.put(REQUEST_PARAM_VALUE_BUILDER, requestParamRequestObjectBuilder);
    requestObjectBuilderMap.put(REQUEST_URI_PARAM_VALUE_BUILDER, null);
    when((oauthServerConfigurationMock.getRequestObjectBuilders())).thenReturn(requestObjectBuilderMap);
    try {
        OIDCRequestObjectUtil.buildRequestObject(oAuthAuthzRequest, oAuth2Parameters);
    } catch (RequestObjectException e) {
        Assert.assertFalse(exceptionNotExpected, errorMsg + " Request Object Building failed due to " + e.getErrorMessage());
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 43 with OAuth2Parameters

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

the class RequestParamRequestObjectBuilderTest method buildRequestObjectTest.

@Test(dataProvider = "TestBuildRequestObjectTest")
public void buildRequestObjectTest(String requestObjectString, Map<String, Object> claims, boolean isSigned, boolean isEncrypted, boolean exceptionNotExpected, String errorMsg) throws Exception {
    mockStatic(IdentityUtil.class);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn("some-server-url");
    OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
    oAuth2Parameters.setTenantDomain("carbon.super");
    oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
    OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    mockStatic(RequestObjectValidatorImpl.class);
    PowerMockito.spy(RequestObjectValidatorImpl.class);
    rsaPrivateKey = (RSAPrivateKey) wso2KeyStore.getKey("wso2carbon", "wso2carbon".toCharArray());
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getTenantId("carbon.super")).thenReturn(-1234);
    when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
    when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate("wso2carbon"));
    RequestObjectValidator requestObjectValidator = new RequestObjectValidatorImpl();
    when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
    RequestObject requestObject;
    RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
    try {
        requestObject = requestParamRequestObjectBuilder.buildRequestObject(requestObjectString, oAuth2Parameters);
        Assert.assertEquals(requestObject.isSigned(), isSigned, errorMsg);
        if (claims != null && !claims.isEmpty()) {
            for (Map.Entry entry : claims.entrySet()) {
                Assert.assertEquals(requestObject.getClaim(entry.getKey().toString()), entry.getValue(), "Request object claim:" + entry.getKey() + " is not properly set.");
            }
        }
    } catch (RequestObjectException e) {
        Assert.assertFalse(exceptionNotExpected, errorMsg + "Building failed due to " + e.getMessage());
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Map(java.util.Map) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 44 with OAuth2Parameters

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

the class RequestObjectValidatorUtil method getJWKSEndpoint.

/**
 * Fetch JWKS endpoint using OAuth2 Parameters.
 *
 * @param oAuth2Parameters oAuth2Parameters
 */
private static String getJWKSEndpoint(OAuth2Parameters oAuth2Parameters) throws RequestObjectException {
    String jwksUri = StringUtils.EMPTY;
    ServiceProviderProperty[] spProperties;
    try {
        spProperties = OAuth2Util.getServiceProvider(oAuth2Parameters.getClientId()).getSpProperties();
    } catch (IdentityOAuth2Exception e) {
        throw new RequestObjectException("Error while getting the service provider for client ID " + oAuth2Parameters.getClientId(), OAuth2ErrorCodes.SERVER_ERROR, e);
    }
    if (spProperties != null) {
        for (ServiceProviderProperty spProperty : spProperties) {
            if (Constants.JWKS_URI.equals(spProperty.getName())) {
                jwksUri = spProperty.getValue();
                if (log.isDebugEnabled()) {
                    log.debug("Found jwks endpoint " + jwksUri + " for service provider with client id " + oAuth2Parameters.getClientId());
                }
                break;
            }
        }
    } else {
        return StringUtils.EMPTY;
    }
    return jwksUri;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty)

Example 45 with OAuth2Parameters

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

the class RequestObjectValidatorUtil method validateSignature.

/**
 * Validate the signature of the request object
 * @param requestObject Request Object
 * @param oAuth2Parameters OAuth2 Parameters
 * @return is signature valid
 * @throws RequestObjectException
 */
public static boolean validateSignature(RequestObject requestObject, OAuth2Parameters oAuth2Parameters) throws RequestObjectException {
    boolean isVerified;
    Certificate certificate = null;
    SignedJWT jwt = requestObject.getSignedJWT();
    try {
        certificate = getCertificateForAlias(oAuth2Parameters.getTenantDomain(), oAuth2Parameters.getClientId());
    } catch (RequestObjectException e) {
        String message = "Error retrieving public certificate for service provider, checking whether a jwks " + "endpoint is configured for the service provider with client_id: " + oAuth2Parameters.getClientId();
        log.warn(message);
        if (log.isDebugEnabled()) {
            log.debug(message, e);
        }
    }
    if (certificate == null) {
        if (log.isDebugEnabled()) {
            log.debug("Public certificate not configured for Service Provider with " + "client_id: " + oAuth2Parameters.getClientId() + " of tenantDomain: " + oAuth2Parameters.getTenantDomain() + ". Fetching the jwks endpoint for validating request object");
        }
        String jwksUri = getJWKSEndpoint(oAuth2Parameters);
        isVerified = isSignatureVerified(jwt, jwksUri);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Public certificate configured for Service Provider with " + "client_id: " + oAuth2Parameters.getClientId() + " of tenantDomain: " + oAuth2Parameters.getTenantDomain() + ". Using public certificate  for validating request object");
        }
        isVerified = isSignatureVerified(jwt, certificate);
    }
    requestObject.setIsSignatureValid(isVerified);
    return isVerified;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) SignedJWT(com.nimbusds.jwt.SignedJWT) Certificate(java.security.cert.Certificate)

Aggregations

OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)40 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)23 HashMap (java.util.HashMap)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Test (org.testng.annotations.Test)19 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)17 Matchers.anyString (org.mockito.Matchers.anyString)14 BeforeTest (org.testng.annotations.BeforeTest)13 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)13 RequestObjectException (org.wso2.carbon.identity.oauth2.RequestObjectException)12 JSONObject (org.json.JSONObject)10 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)9 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)8 ArrayList (java.util.ArrayList)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)7 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)7 SessionDataCacheKey (org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)7 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)7 URI (java.net.URI)6