Search in sources :

Example 1 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class FrameworkUtils method triggerSessionExpireEvent.

/**
 * Trigger SESSION_EXPIRE event on session expiry due to a session idle timeout or a remember me session time out.
 *
 * @param request        HttpServletRequest.
 * @param context        Authentication context.
 * @param sessionContext Session context.
 * @throws FrameworkException Error in triggering the session expiry event.
 */
private static void triggerSessionExpireEvent(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext) throws FrameworkException {
    AuthenticatedUser authenticatedUser = new AuthenticatedUser();
    if (sessionContext != null) {
        Object authenticatedUserObj = sessionContext.getProperty(FrameworkConstants.AUTHENTICATED_USER);
        if (authenticatedUserObj instanceof AuthenticatedUser) {
            authenticatedUser = (AuthenticatedUser) authenticatedUserObj;
        }
        context.setSubject(authenticatedUser);
        IdentityEventService eventService = FrameworkServiceDataHolder.getInstance().getIdentityEventService();
        try {
            Map<String, Object> eventProperties = new HashMap<>();
            eventProperties.put(IdentityEventConstants.EventProperty.REQUEST, request);
            eventProperties.put(IdentityEventConstants.EventProperty.CONTEXT, context);
            eventProperties.put(IdentityEventConstants.EventProperty.SESSION_CONTEXT, sessionContext);
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put(FrameworkConstants.AnalyticsAttributes.USER, authenticatedUser);
            paramMap.put(FrameworkConstants.AnalyticsAttributes.SESSION_ID, context.getSessionIdentifier());
            Map<String, Object> unmodifiableParamMap = Collections.unmodifiableMap(paramMap);
            eventProperties.put(IdentityEventConstants.EventProperty.PARAMS, unmodifiableParamMap);
            Event event = new Event(IdentityEventConstants.EventName.SESSION_EXPIRE.name(), eventProperties);
            eventService.handleEvent(event);
        } catch (IdentityEventException e) {
            throw new FrameworkException("Error in triggering session expire event for the session: " + context.getSessionIdentifier() + " of user: " + authenticatedUser.toFullQualifiedUsername(), e);
        }
    }
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) HashMap(java.util.HashMap) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) Event(org.wso2.carbon.identity.event.event.Event) JSONObject(org.json.JSONObject) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService)

Example 2 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project carbon-identity-framework by wso2.

the class RoleManagementEventPublisherProxy method doPublishEvent.

private void doPublishEvent(Event event) {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Event: " + event.getEventName() + " is published for the role management operation in " + "the tenant with the tenantId: " + event.getEventProperties().get(IdentityEventConstants.EventProperty.TENANT_ID));
        }
        IdentityEventService eventService = RoleManagementServiceComponentHolder.getInstance().getIdentityEventService();
        eventService.handleEvent(event);
    } catch (IdentityEventException e) {
        log.error("Error while publishing the event: " + event.getEventName() + ".", e);
    }
}
Also used : IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService)

Example 3 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest1.

@Test(dataProvider = "provideHandleOAuthAuthorizationRequest1Data", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object spObj, String savedDisplayName) throws Exception {
    ServiceProvider sp = (ServiceProvider) spObj;
    sp.setApplicationName(APP_NAME);
    mockApplicationManagementService(sp);
    mockOAuthServerConfiguration();
    mockEndpointUtil(false);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(true);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
    when(oAuthServerConfiguration.isShowDisplayNameInConsentPage()).thenReturn(showDisplayName);
    Method handleOAuthAuthorizationRequest = authzEndpointObject.getClass().getDeclaredMethod("handleOAuthAuthorizationRequest", OAuthMessage.class);
    handleOAuthAuthorizationRequest.setAccessible(true);
    SessionDataCache sessionDataCache = mock(SessionDataCache.class);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    final SessionDataCacheEntry[] cacheEntry = new SessionDataCacheEntry[1];
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) {
            cacheEntry[0] = (SessionDataCacheEntry) invocation.getArguments()[1];
            return null;
        }
    }).when(sessionDataCache).addToCache(any(SessionDataCacheKey.class), any(SessionDataCacheEntry.class));
    when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
    when(oAuthMessage.getClientId()).thenReturn(CLIENT_ID_VALUE);
    handleOAuthAuthorizationRequest.invoke(authzEndpointObject, oAuthMessage);
    assertNotNull(cacheEntry[0], "Parameters not saved in cache");
    assertEquals(cacheEntry[0].getoAuth2Parameters().getDisplayName(), savedDisplayName);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) Matchers.anyString(org.mockito.Matchers.anyString) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService 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 5 with IdentityEventService

use of org.wso2.carbon.identity.event.services.IdentityEventService in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticatorTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    smsotpAuthenticator = new SMSOTPAuthenticator();
    mockStatic(SMSOTPServiceDataHolder.class);
    when(SMSOTPServiceDataHolder.getInstance()).thenReturn(sMSOTPServiceDataHolder);
    when(sMSOTPServiceDataHolder.getIdentityEventService()).thenReturn(identityEventService);
    Mockito.doNothing().when(identityEventService).handleEvent(anyObject());
    when(httpServletRequest.getHeaderNames()).thenReturn(requestHeaders);
    initMocks(this);
}
Also used : SMSOTPAuthenticator(org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator) BeforeMethod(org.testng.annotations.BeforeMethod)

Aggregations

IdentityEventService (org.wso2.carbon.identity.event.services.IdentityEventService)18 HashMap (java.util.HashMap)13 Test (org.testng.annotations.Test)10 IdentityEventException (org.wso2.carbon.identity.event.IdentityEventException)10 Event (org.wso2.carbon.identity.event.event.Event)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 BeforeTest (org.testng.annotations.BeforeTest)8 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 Matchers.anyString (org.mockito.Matchers.anyString)5 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)4 AfterTest (org.testng.annotations.AfterTest)4 OAuthServerConfiguration (org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)3 Method (java.lang.reflect.Method)2 Instant (java.time.Instant)2 Hashtable (java.util.Hashtable)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpMethod (javax.ws.rs.HttpMethod)2