Search in sources :

Example 6 with RequestObject

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

the class DefaultOIDCProcessor method getResponse.

public OIDProviderConfigResponse getResponse(HttpServletRequest request, String tenantDomain) throws OIDCDiscoveryEndPointException, ServerConfigurationException {
    OIDCProviderRequestBuilder requestBuilder = new DefaultOIDCProviderRequestBuilder();
    OIDProviderRequest requestObject = requestBuilder.buildRequest(request, tenantDomain);
    ProviderConfigBuilder responseBuilder = new ProviderConfigBuilder();
    return responseBuilder.buildOIDProviderConfig(requestObject);
}
Also used : ProviderConfigBuilder(org.wso2.carbon.identity.discovery.builders.ProviderConfigBuilder) DefaultOIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder) DefaultOIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder) OIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder)

Example 7 with RequestObject

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

the class OIDCRequestObjectUtilTest method testBuildRequestObjectURITest.

@Test(expectedExceptions = { RequestObjectException.class })
public void testBuildRequestObjectURITest() throws Exception {
    OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
    oAuth2Parameters.setTenantDomain("carbon.super");
    oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
    OAuthAuthzRequest oAuthAuthzRequest = mock(OAuthAuthzRequest.class);
    when(oAuthAuthzRequest.getParam(Constants.REQUEST_URI)).thenReturn("some-uri");
    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);
    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.toString()).when(requestObjectValidator, "getTokenEpURL", anyString());
    KeyStoreManager keyStoreManager = Mockito.mock(KeyStoreManager.class);
    ConcurrentHashMap<String, KeyStoreManager> mtKeyStoreManagers = new ConcurrentHashMap();
    mtKeyStoreManagers.put(String.valueOf(SUPER_TENANT_ID), keyStoreManager);
    WhiteboxImpl.setInternalState(KeyStoreManager.class, "mtKeyStoreManagers", mtKeyStoreManagers);
    Mockito.when(keyStoreManager.getPrimaryKeyStore()).thenReturn(wso2KeyStore);
    Mockito.when(keyStoreManager.getKeyStore("wso2carbon.jks")).thenReturn(wso2KeyStore);
    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);
    RequestObject requestObject = OIDCRequestObjectUtil.buildRequestObject(oAuthAuthzRequest, oAuth2Parameters);
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) KeyStoreManager(org.wso2.carbon.core.util.KeyStoreManager) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) 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 8 with RequestObject

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

the class RequestObjectValidatorImplTest method testValidateRequestObj.

@Test(dataProvider = "provideJWT")
public void testValidateRequestObj(String jwt, boolean isSigned, boolean isEncrypted, boolean validSignature, boolean validRequestObj, String errorMsg) throws Exception {
    OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
    oAuth2Parameters.setTenantDomain(SUPER_TENANT_DOMAIN_NAME);
    oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
    mockStatic(IdentityUtil.class);
    when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn("some-server-url");
    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());
    OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    rsaPrivateKey = (RSAPrivateKey) wso2KeyStore.getKey("wso2carbon", "wso2carbon".toCharArray());
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getTenantId(SUPER_TENANT_DOMAIN_NAME)).thenReturn(SUPER_TENANT_ID);
    when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
    // Mock OAuth2Util returning public cert of the service provider
    when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate(CLIENT_PUBLIC_CERT_ALIAS));
    RequestObjectValidatorImpl requestObjectValidator = PowerMockito.spy(new RequestObjectValidatorImpl());
    RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
    when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
    mockIdentityProviderManager();
    PowerMockito.mockStatic(IdentityApplicationManagementUtil.class);
    FederatedAuthenticatorConfig config = new FederatedAuthenticatorConfig();
    when(IdentityApplicationManagementUtil.getFederatedAuthenticator(any(), any())).thenReturn(config);
    Property property = new Property();
    property.setValue(SOME_SERVER_URL);
    when(IdentityApplicationManagementUtil.getProperty(config.getProperties(), "IdPEntityId")).thenReturn(property);
    RequestObject requestObject = requestParamRequestObjectBuilder.buildRequestObject(jwt, oAuth2Parameters);
    Assert.assertEquals(requestParamRequestObjectBuilder.isEncrypted(jwt), isEncrypted, "Payload is encrypted:" + isEncrypted);
    Assert.assertEquals(requestObjectValidator.isSigned(requestObject), isSigned, "Request object isSigned: " + isSigned);
    if (isSigned) {
        Assert.assertEquals(requestObjectValidator.validateSignature(requestObject, oAuth2Parameters), validSignature, errorMsg + "Request Object Signature Validation failed.");
    }
    boolean validObject;
    try {
        validObject = requestObjectValidator.validateRequestObject(requestObject, oAuth2Parameters);
    } catch (Exception e) {
        validObject = false;
    }
    Assert.assertEquals(validObject, validRequestObj, errorMsg);
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Property(org.wso2.carbon.identity.application.common.model.Property) 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 9 with RequestObject

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

the class RequestParamRequestObjectBuilder method buildRequestObject.

/**
 * Builds request object which comes as the value of the request query parameter of OIDC authorization request
 *
 * @param requestObjectParam request object
 * @throws RequestObjectException
 */
@Override
public RequestObject buildRequestObject(String requestObjectParam, OAuth2Parameters oAuth2Parameters) throws RequestObjectException {
    RequestObject requestObject = new RequestObject();
    // Making a copy of requestObjectParam to prevent editing initial reference
    String requestObjectParamValue = requestObjectParam;
    if (isEncrypted(requestObjectParamValue)) {
        requestObjectParamValue = decrypt(requestObjectParamValue, oAuth2Parameters);
        if (isEmpty(requestObjectParamValue)) {
            return requestObject;
        }
    }
    setRequestObjectValues(requestObjectParamValue, requestObject);
    if (log.isDebugEnabled()) {
        log.debug("Request Object extracted from the request: " + requestObjectParam);
    }
    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Request object parsed successfully.", "parse-request-object", null);
    return requestObject;
}
Also used : RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject)

Example 10 with RequestObject

use of org.wso2.carbon.identity.openidconnect.model.RequestObject in project identity-governance by wso2-extensions.

the class PasswordRecoveryReCaptchaConnector method preValidate.

@Override
public CaptchaPreValidationResponse preValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException {
    CaptchaPreValidationResponse preValidationResponse = new CaptchaPreValidationResponse();
    boolean forgotPasswordRecaptchaEnabled = checkReCaptchaEnabledForForgotPassoword(servletRequest, FORGOT_PASSWORD_RECAPTCHA_ENABLE);
    String pathUrl = ((HttpServletRequest) servletRequest).getRequestURI();
    if (forgotPasswordRecaptchaEnabled && (CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(pathUrl, ACCOUNT_SECURITY_QUESTIONS_URL) || CaptchaUtil.isPathAvailable(pathUrl, RECOVER_PASSWORD_URL))) {
        preValidationResponse.setCaptchaValidationRequired(true);
    }
    // Handle recover with Email option.
    if (pathUrl.equals(RECOVER_PASSWORD_URL)) {
        return preValidationResponse;
    }
    // Handle recover with security questions option.
    HttpServletRequest httpServletRequestWrapper;
    try {
        httpServletRequestWrapper = new CaptchaHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        preValidationResponse.setWrappedHttpServletRequest(httpServletRequestWrapper);
    } catch (IOException e) {
        log.error("Error occurred while wrapping ServletRequest.", e);
        return preValidationResponse;
    }
    String path = httpServletRequestWrapper.getRequestURI();
    User user = new User();
    boolean initializationFlow = false;
    if (CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTION_URL) || CaptchaUtil.isPathAvailable(path, ACCOUNT_SECURITY_QUESTIONS_URL)) {
        user.setUserName(servletRequest.getParameter("username"));
        if (StringUtils.isNotBlank(servletRequest.getParameter("realm"))) {
            user.setUserStoreDomain(servletRequest.getParameter("realm"));
        } else {
            user.setUserStoreDomain(IdentityUtil.getPrimaryDomainName());
        }
        user.setTenantDomain(servletRequest.getParameter("tenant-domain"));
        initializationFlow = true;
    } else {
        JsonObject requestObject;
        try {
            try (InputStream in = httpServletRequestWrapper.getInputStream()) {
                requestObject = new JsonParser().parse(IOUtils.toString(in)).getAsJsonObject();
            }
        } catch (IOException e) {
            return preValidationResponse;
        }
        UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
        try {
            UserRecoveryData userRecoveryData = userRecoveryDataStore.load(requestObject.get("key").getAsString());
            if (userRecoveryData != null) {
                user = userRecoveryData.getUser();
            }
        } catch (IdentityRecoveryException e) {
            return preValidationResponse;
        }
    }
    if (StringUtils.isBlank(user.getUserName())) {
        // Invalid Request
        return preValidationResponse;
    }
    if (StringUtils.isBlank(user.getTenantDomain())) {
        user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }
    Property[] connectorConfigs;
    try {
        connectorConfigs = identityGovernanceService.getConfiguration(new String[] { RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE, RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS }, user.getTenantDomain());
    } catch (IdentityGovernanceException e) {
        throw new CaptchaServerException("Unable to retrieve connector configs.", e);
    }
    String connectorEnabled = null;
    String maxAttemptsStr = null;
    for (Property connectorConfig : connectorConfigs) {
        if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_ENABLE).equals(connectorConfig.getName())) {
            connectorEnabled = connectorConfig.getValue();
        } else if ((RECOVERY_QUESTION_PASSWORD_RECAPTCHA_MAX_FAILED_ATTEMPTS).equals(connectorConfig.getName())) {
            maxAttemptsStr = connectorConfig.getValue();
        }
    }
    if (!Boolean.parseBoolean(connectorEnabled)) {
        return preValidationResponse;
    }
    if (StringUtils.isBlank(maxAttemptsStr) || !NumberUtils.isNumber(maxAttemptsStr)) {
        log.warn("Invalid configuration found in the PasswordRecoveryReCaptchaConnector for the tenant - " + user.getTenantDomain());
        return preValidationResponse;
    }
    int maxFailedAttempts = Integer.parseInt(maxAttemptsStr);
    int tenantId;
    try {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } catch (Exception e) {
        // Invalid tenant
        return preValidationResponse;
    }
    try {
        if (CaptchaDataHolder.getInstance().getAccountLockService().isAccountLocked(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain())) {
            return preValidationResponse;
        }
    } catch (AccountLockServiceException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while validating if account is locked for user: " + user.getUserName() + " of user " + "store domain: " + user.getUserStoreDomain() + " and tenant domain: " + user.getTenantDomain());
        }
        return preValidationResponse;
    }
    Map<String, String> claimValues = CaptchaUtil.getClaimValues(user, tenantId, new String[] { FAIL_ATTEMPTS_CLAIM });
    if (claimValues == null || claimValues.isEmpty()) {
        // Invalid user
        return preValidationResponse;
    }
    int currentFailedAttempts = 0;
    if (NumberUtils.isNumber(claimValues.get(FAIL_ATTEMPTS_CLAIM))) {
        currentFailedAttempts = Integer.parseInt(claimValues.get(FAIL_ATTEMPTS_CLAIM));
    }
    HttpServletResponse httpServletResponse = ((HttpServletResponse) servletResponse);
    if (currentFailedAttempts > maxFailedAttempts) {
        if (initializationFlow) {
            httpServletResponse.setHeader("reCaptcha", "true");
            httpServletResponse.setHeader("reCaptchaKey", CaptchaDataHolder.getInstance().getReCaptchaSiteKey());
            httpServletResponse.setHeader("reCaptchaAPI", CaptchaDataHolder.getInstance().getReCaptchaAPIUrl());
        } else {
            preValidationResponse.setCaptchaValidationRequired(true);
            preValidationResponse.setMaxFailedLimitReached(true);
            addPostValidationData(servletRequest);
        }
    } else if (currentFailedAttempts == maxFailedAttempts && !initializationFlow) {
        addPostValidationData(servletRequest);
    }
    return preValidationResponse;
}
Also used : AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) CaptchaHttpServletRequestWrapper(org.wso2.carbon.identity.captcha.util.CaptchaHttpServletRequestWrapper) User(org.wso2.carbon.identity.application.common.model.User) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) HttpServletResponse(javax.servlet.http.HttpServletResponse) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IOException(java.io.IOException) CaptchaClientException(org.wso2.carbon.identity.captcha.exception.CaptchaClientException) CaptchaException(org.wso2.carbon.identity.captcha.exception.CaptchaException) IOException(java.io.IOException) CaptchaServerException(org.wso2.carbon.identity.captcha.exception.CaptchaServerException) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) AccountLockServiceException(org.wso2.carbon.identity.handler.event.account.lock.exception.AccountLockServiceException) IdentityGovernanceException(org.wso2.carbon.identity.governance.IdentityGovernanceException) CaptchaPreValidationResponse(org.wso2.carbon.identity.captcha.connector.CaptchaPreValidationResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRecoveryData(org.wso2.carbon.identity.recovery.model.UserRecoveryData) UserRecoveryDataStore(org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore) IdentityRecoveryException(org.wso2.carbon.identity.recovery.IdentityRecoveryException) Property(org.wso2.carbon.identity.application.common.model.Property) JsonParser(com.google.gson.JsonParser)

Aggregations

RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)11 RequestObjectException (org.wso2.carbon.identity.oauth2.RequestObjectException)8 HashMap (java.util.HashMap)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 BeforeTest (org.testng.annotations.BeforeTest)4 Test (org.testng.annotations.Test)4 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)4 Map (java.util.Map)3 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)3 JsonObject (com.google.gson.JsonObject)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Matchers.anyString (org.mockito.Matchers.anyString)2 Property (org.wso2.carbon.identity.application.common.model.Property)2 InvalidRequestException (org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException)2 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)2 JsonElement (com.google.gson.JsonElement)1 JsonParseException (com.google.gson.JsonParseException)1 JsonParser (com.google.gson.JsonParser)1