org.keycloak.events.EventType Java Examples

The following examples show how to use org.keycloak.events.EventType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * protocol independent page for restart of the flow
 *
 * @return
 */
@Path(RESTART_PATH)
@GET
public Response restartSession(@QueryParam(AUTH_SESSION_ID) String authSessionId, // optional, can get from cookie instead
                               @QueryParam(Constants.CLIENT_ID) String clientId,
                               @QueryParam(Constants.TAB_ID) String tabId) {
    event.event(EventType.RESTART_AUTHENTICATION);
    SessionCodeChecks checks = new SessionCodeChecks(realm, session.getContext().getUri(), request, clientConnection, session, event, authSessionId, null, null, clientId,  tabId, null);

    AuthenticationSessionModel authSession = checks.initialVerifyAuthSession();
    if (authSession == null) {
        return checks.getResponse();
    }

    String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
    if (flowPath == null) {
        flowPath = AUTHENTICATE_PATH;
    }

    AuthenticationProcessor.resetFlow(authSession, flowPath);

    URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getClient().getClientId(), tabId);
    logger.debugf("Flow restart requested. Redirecting to %s", redirectUri);
    return Response.status(Response.Status.FOUND).location(redirectUri).build();
}
 
Example #2
Source File: ResetPasswordTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void resetPasswordCancelChangeUser() throws IOException, MessagingException {
    initiateResetPasswordFromResetPasswordPage("test-user@localhost");

    events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).detail(Details.USERNAME, "test-user@localhost")
            .session((String) null)
            .detail(Details.EMAIL, "test-user@localhost").assertEvent();

    loginPage.login("[email protected]", "password");

    EventRepresentation loginEvent = events.expectLogin().user(userId).detail(Details.USERNAME, "[email protected]").assertEvent();

    String code = oauth.getCurrentQuery().get("code");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");

    assertEquals(200, tokenResponse.getStatusCode());
    assertEquals(userId, oauth.verifyToken(tokenResponse.getAccessToken()).getSubject());

    events.expectCodeToToken(loginEvent.getDetails().get(Details.CODE_ID), loginEvent.getSessionId()).user(userId).assertEvent();
}
 
Example #3
Source File: JpaEventStoreProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static Event convertEvent(EventEntity eventEntity) {
    Event event = new Event();
    event.setTime(eventEntity.getTime());
    event.setType(EventType.valueOf(eventEntity.getType()));
    event.setRealmId(eventEntity.getRealmId());
    event.setClientId(eventEntity.getClientId());
    event.setUserId(eventEntity.getUserId());
    event.setSessionId(eventEntity.getSessionId());
    event.setIpAddress(eventEntity.getIpAddress());
    event.setError(eventEntity.getError());
    try {
        Map<String, String> details = mapper.readValue(eventEntity.getDetailsJson(), mapType);
        event.setDetails(details);
    } catch (IOException ex) {
        logger.error("Failed to read log details", ex);
    }
    return event;
}
 
Example #4
Source File: LDAPUserLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void verifyLoginFailed(String username, String password) {
    // Clear the events queue before the actual test to catch all errors properly
    events.clear();
    // Run the test actions
    loginPage.open();
    loginPage.login(username, password);
    Assert.assertEquals("Invalid username or password.", loginPage.getError());

    if (username.equals(DEFAULT_TEST_USERS.get("INVALID_USER_EMAIL")) || username.equals(DEFAULT_TEST_USERS.get("INVALID_USER_NAME"))) {

        events.expect(EventType.LOGIN_ERROR).user((String) null).error(Errors.USER_NOT_FOUND).assertEvent();

    } else if (username.equals(DEFAULT_TEST_USERS.get("VALID_USER_EMAIL")) || username.equals(DEFAULT_TEST_USERS.get("VALID_USER_NAME"))) {

        List<UserRepresentation> knownUsers = getAdminClient().realm(TEST_REALM_NAME).users().search(DEFAULT_TEST_USERS.get("VALID_USER_NAME"));
        Assert.assertTrue(!knownUsers.isEmpty());
        final String userId = knownUsers.get(0).getId();
        events.expect(EventType.LOGIN_ERROR).user(userId).error(Errors.INVALID_USER_CREDENTIALS).assertEvent();

    }
}
 
Example #5
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * protocol independent login page entry point
 *
 * @param code
 * @return
 */
@Path(AUTHENTICATE_PATH)
@GET
public Response authenticate(@QueryParam(AUTH_SESSION_ID) String authSessionId, // optional, can get from cookie instead
                             @QueryParam(SESSION_CODE) String code,
                             @QueryParam(Constants.EXECUTION) String execution,
                             @QueryParam(Constants.CLIENT_ID) String clientId,
                             @QueryParam(Constants.TAB_ID) String tabId) {
    event.event(EventType.LOGIN);

    SessionCodeChecks checks = checksForCode(authSessionId, code, execution, clientId, tabId, AUTHENTICATE_PATH);
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        return checks.getResponse();
    }

    AuthenticationSessionModel authSession = checks.getAuthenticationSession();
    boolean actionRequest = checks.isActionRequest();

    processLocaleParam(authSession);

    return processAuthentication(actionRequest, execution, authSession, null);
}
 
Example #6
Source File: AppInitiatedActionResetPasswordTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void resetPasswordRequiresReAuth() throws Exception {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");

    events.expectLogin().assertEvent();

    setTimeOffset(350);

    // Should prompt for re-authentication
    doAIA();

    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");

    changePasswordPage.assertCurrent();
    assertTrue(changePasswordPage.isCancelDisplayed());

    changePasswordPage.changePassword("new-password", "new-password");

    events.expectRequiredAction(EventType.UPDATE_PASSWORD).assertEvent();
    assertKcActionStatus("success");
}
 
Example #7
Source File: PassThroughRegistration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    context.getEvent().detail(Details.USERNAME, username)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.EMAIL, email)
    ;
    UserModel user = context.getSession().users().addUser(context.getRealm(), username);
    user.setEnabled(true);

    user.setEmail(email);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    context.setUser(user);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId())
            .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri())
            .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
    context.success();
}
 
Example #8
Source File: ResetPasswordTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void resetPasswordDisabledUser() throws IOException, MessagingException, InterruptedException {
    UserRepresentation user = findUser("login-test");
    try {
        user.setEnabled(false);
        updateUser(user);

        initiateResetPasswordFromResetPasswordPage("login-test");

        assertEquals(0, greenMail.getReceivedMessages().length);

        events.expectRequiredAction(EventType.RESET_PASSWORD).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("user_disabled").assertEvent();
    } finally {
        user.setEnabled(true);
        updateUser(user);
    }
}
 
Example #9
Source File: ResetPasswordTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void resetPasswordNoEmail() throws IOException, MessagingException, InterruptedException {
    final String email;

    UserRepresentation user = findUser("login-test");
    email = user.getEmail();

    try {
        user.setEmail("");
        updateUser(user);

        initiateResetPasswordFromResetPasswordPage("login-test");

        assertEquals(0, greenMail.getReceivedMessages().length);

        events.expectRequiredAction(EventType.RESET_PASSWORD_ERROR).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("invalid_email").assertEvent();
    } finally {
        user.setEmail(email);
        updateUser(user);
    }
}
 
Example #10
Source File: SAMLEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response basicChecks(String samlRequest, String samlResponse) {
    if (!checkSsl()) {
        event.event(EventType.LOGIN);
        event.error(Errors.SSL_REQUIRED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
    }
    if (!realm.isEnabled()) {
        event.event(EventType.LOGIN_ERROR);
        event.error(Errors.REALM_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
    }

    if (samlRequest == null && samlResponse == null) {
        event.event(EventType.LOGIN);
        event.error(Errors.INVALID_REQUEST);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);

    }
    return null;
}
 
Example #11
Source File: ConsoleVerifyEmail.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent().clone().event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, context.getUser().getEmail());
    String code = context.getAuthenticationSession().getAuthNote(Constants.VERIFY_EMAIL_CODE);
    if (code == null) {
        requiredActionChallenge(context);
        return;
    }

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String emailCode = formData.getFirst(EMAIL_CODE);

    if (!code.equals(emailCode)) {
        context.challenge(
                challenge(context).message(Messages.INVALID_CODE)
        );
        event.error(Errors.INVALID_CODE);
        return;
    }
    event.success();
    context.success();
}
 
Example #12
Source File: ConsoleUpdateTotp.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent();
    event.event(EventType.UPDATE_TOTP);
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String challengeResponse = formData.getFirst("totp");
    String totpSecret = context.getAuthenticationSession().getAuthNote("totpSecret");
    String userLabel = formData.getFirst("userLabel");

    OTPPolicy policy = context.getRealm().getOTPPolicy();
    OTPCredentialModel credentialModel = OTPCredentialModel.createFromPolicy(context.getRealm(), totpSecret, userLabel);
    if (Validation.isBlank(challengeResponse)) {
        context.challenge(challenge(context).message(Messages.MISSING_TOTP));
        return;
    } else if (!CredentialValidation.validOTP(challengeResponse, credentialModel, policy.getLookAheadWindow())) {
        context.challenge(challenge(context).message(Messages.INVALID_TOTP));
        return;
    }

    if (!CredentialHelper.createOTPCredential(context.getSession(), context.getRealm(), context.getUser(), challengeResponse, credentialModel)) {
        context.challenge(challenge(context).message(Messages.INVALID_TOTP));
        return;
    }
    context.getAuthenticationSession().removeAuthNote("totpSecret");
    context.success();
}
 
Example #13
Source File: PrometheusExporterTest.java    From keycloak-metrics-spi with Apache License 2.0 6 votes vote down vote up
private Event createEvent(EventType type, String realm, String clientId, String error, Tuple<String, String>... tuples) {
    final Event event = new Event();
    event.setType(type);
    event.setRealmId(realm);
    event.setClientId(clientId);
    if (tuples != null) {
        event.setDetails(new HashMap<>());
        for (Tuple<String, String> tuple : tuples) {
            event.getDetails().put(tuple.left, tuple.right);
        }
    } else {
        event.setDetails(Collections.emptyMap());
    }

    if (error != null) {
        event.setError(error);
    }
    return event;
}
 
Example #14
Source File: TrustStoreEmailTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyEmailWithSslWrongCertificate() throws Exception {
    UserRepresentation user = ApiUtil.findUserByUsername(testRealm(), "test-user@localhost");

    SslMailServer.startWithSsl(this.getClass().getClassLoader().getResource(SslMailServer.INVALID_KEY).getFile());
    accountManagement.navigateTo();
    loginPage.form().login(user.getUsername(), "password");

    events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL_ERROR)
            .error(Errors.EMAIL_SEND_FAILED)
            .user(user.getId())
            .client("account")
            .detail(Details.USERNAME, "test-user@localhost")
            .detail(Details.EMAIL, "test-user@localhost")
            .removeDetail(Details.REDIRECT_URI)
            .assertEvent();

    // Email wasn't send
    Assert.assertNull(SslMailServer.getLastReceivedMessage());

    // Email wasn't send, but we won't notify end user about that. Admin is aware due to the error in the logs and the SEND_VERIFY_EMAIL_ERROR event.
    assertEquals("You need to verify your email address to activate your account.",
            testRealmVerifyEmailPage.feedbackMessage().getText());
}
 
Example #15
Source File: EmailEventListenerProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void init(Config.Scope config) {
    String[] include = config.getArray("include-events");
    if (include != null) {
        for (String i : include) {
            includedEvents.add(EventType.valueOf(i.toUpperCase()));
        }
    } else {
        includedEvents.addAll(SUPPORTED_EVENTS);
    }

    String[] exclude = config.getArray("exclude-events");
    if (exclude != null) {
        for (String e : exclude) {
            includedEvents.remove(EventType.valueOf(e.toUpperCase()));
        }
    }
}
 
Example #16
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path(RESET_CREDENTIALS_PATH)
@POST
public Response resetCredentialsPOST(@QueryParam(AUTH_SESSION_ID) String authSessionId, // optional, can get from cookie instead
                                     @QueryParam(SESSION_CODE) String code,
                                     @QueryParam(Constants.EXECUTION) String execution,
                                     @QueryParam(Constants.CLIENT_ID) String clientId,
                                     @QueryParam(Constants.TAB_ID) String tabId,
                                     @QueryParam(Constants.KEY) String key) {
    if (key != null) {
        return handleActionToken(key, execution, clientId, tabId);
    }

    event.event(EventType.RESET_PASSWORD);

    return resetCredentials(authSessionId, code, execution, clientId, tabId);
}
 
Example #17
Source File: TokenRevocationEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revoke() {
    event.event(EventType.REVOKE_GRANT);

    cors = Cors.add(request).auth().allowedMethods("POST").auth().exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS);

    checkSsl();
    checkRealm();
    checkClient();

    formParams = request.getDecodedFormParameters();

    checkToken();
    checkIssuedFor();

    checkUser();
    revokeClient();

    event.detail(Details.REVOKED_CLIENT, client.getClientId()).success();

    session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
    return cors.builder(Response.ok()).build();
}
 
Example #18
Source File: AccountRestServiceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
 public void testPostPasswordUpdate() throws IOException {
     //Get the time of lastUpdate
     AccountCredentialResource.PasswordDetails initialDetails = getPasswordDetails();

     // ignore login event
     events.poll();

     //Change the password
     updatePassword("password", "Str0ng3rP4ssw0rd", 204);

     //Get the new value for lastUpdate
     AccountCredentialResource.PasswordDetails updatedDetails = getPasswordDetails();
     assertTrue(initialDetails.getLastUpdate() < updatedDetails.getLastUpdate());
     Assert.assertEquals(EventType.UPDATE_PASSWORD.name(), events.poll().getType());

     //Try to change password again; should fail as current password is incorrect
     updatePassword("password", "Str0ng3rP4ssw0rd", 400);

     //Verify that lastUpdate hasn't changed
     AccountCredentialResource.PasswordDetails finalDetails = getPasswordDetails();
     assertEquals(updatedDetails.getLastUpdate(), finalDetails.getLastUpdate());

     //Change the password back
     updatePassword("Str0ng3rP4ssw0rd", "password", 204);
}
 
Example #19
Source File: RequiredActionMultipleActionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String updatePassword(String codeId) {
    changePasswordPage.changePassword("new-password", "new-password");

    AssertEvents.ExpectedEvent expectedEvent = events.expectRequiredAction(EventType.UPDATE_PASSWORD);
    if (codeId != null) {
        expectedEvent.detail(Details.CODE_ID, codeId);
    }
    return expectedEvent.assertEvent().getDetails().get(Details.CODE_ID);
}
 
Example #20
Source File: ResetPasswordTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void resetPasswordWrongSmtp() throws IOException, MessagingException, InterruptedException {
    final String[] host = new String[1];

    Map<String, String> smtpConfig = new HashMap<>();
    smtpConfig.putAll(testRealm().toRepresentation().getSmtpServer());
    host[0] =  smtpConfig.get("host");
    smtpConfig.put("host", "invalid_host");
    RealmRepresentation realmRep = testRealm().toRepresentation();
    Map<String, String> oldSmtp = realmRep.getSmtpServer();

    try {
        realmRep.setSmtpServer(smtpConfig);
        testRealm().update(realmRep);

        loginPage.open();
        loginPage.resetPassword();

        resetPasswordPage.assertCurrent();

        resetPasswordPage.changePassword("login-test");

        errorPage.assertCurrent();

        assertEquals("Failed to send email, please try again later.", errorPage.getError());

        assertEquals(0, greenMail.getReceivedMessages().length);

        events.expectRequiredAction(EventType.SEND_RESET_PASSWORD_ERROR).user(userId)
                .session((String)null)
                .detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error(Errors.EMAIL_SEND_FAILED).assertEvent();
    } finally {
        // Revert SMTP back
        realmRep.setSmtpServer(oldSmtp);
        testRealm().update(realmRep);
    }
}
 
Example #21
Source File: LinkedAccountsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{providerId}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeLinkedAccount(@PathParam("providerId") String providerId) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    
    String errorMessage = checkCommonPreconditions(providerId);
    if (errorMessage != null) {
        return ErrorResponse.error(errorMessage, Response.Status.BAD_REQUEST);
    }
    
    FederatedIdentityModel link = session.users().getFederatedIdentity(user, providerId, realm);
    if (link == null) {
        return ErrorResponse.error(Messages.FEDERATED_IDENTITY_NOT_ACTIVE, Response.Status.BAD_REQUEST);
    }

    // Removing last social provider is not possible if you don't have other possibility to authenticate
    if (!(session.users().getFederatedIdentities(user, realm).size() > 1 || user.getFederationLink() != null || isPasswordSet())) {
        return ErrorResponse.error(Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER, Response.Status.BAD_REQUEST);
    }
    
    session.users().removeFederatedIdentity(realm, user, providerId);

    logger.debugv("Social provider {0} removed successfully from user {1}", providerId, user.getUsername());

    event.event(EventType.REMOVE_FEDERATED_IDENTITY).client(auth.getClient()).user(auth.getUser())
            .detail(Details.USERNAME, auth.getUser().getUsername())
            .detail(Details.IDENTITY_PROVIDER, link.getIdentityProvider())
            .detail(Details.IDENTITY_PROVIDER_USERNAME, link.getUserName())
            .success();

    return Cors.add(request, Response.noContent()).auth().allowedOrigins(auth.getToken()).build();
}
 
Example #22
Source File: ResetPasswordTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void updateForgottenPassword(UserRepresentation user, String clientId, String redirectUri, String requiredUri) throws IOException {
    final int emailCount = greenMail.getReceivedMessages().length;

    doForgotPassword(user.getUsername());
    assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage());

    events.expectRequiredAction(EventType.SEND_RESET_PASSWORD)
            .user(user.getId())
            .client(clientId)
            .detail(Details.REDIRECT_URI, redirectUri)
            .detail(Details.USERNAME, user.getUsername())
            .detail(Details.EMAIL, user.getEmail())
            .session((String) null)
            .assertEvent();

    assertEquals(emailCount + 1, greenMail.getReceivedMessages().length);

    final MimeMessage message = greenMail.getReceivedMessages()[emailCount];
    final String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);

    BrowserTabUtil util = BrowserTabUtil.getInstanceAndSetEnv(driver);
    util.newTab(changePasswordUrl.trim());

    changePasswordOnUpdatePage(driver);

    events.expectRequiredAction(EventType.UPDATE_PASSWORD)
            .detail(Details.REDIRECT_URI, redirectUri)
            .client(clientId)
            .user(user.getId()).detail(Details.USERNAME, user.getUsername()).assertEvent();

    assertThat(driver.getCurrentUrl(), Matchers.containsString(requiredUri));
}
 
Example #23
Source File: TrustStoreEmailTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyEmailWithSslWrongHostname() throws Exception {
    UserRepresentation user = ApiUtil.findUserByUsername(testRealm(), "test-user@localhost");

    RealmRepresentation realmRep = testRealm().toRepresentation();
    realmRep.getSmtpServer().put("host", "localhost.localdomain");
    testRealm().update(realmRep);

    try {
        SslMailServer.startWithSsl(this.getClass().getClassLoader().getResource(SslMailServer.PRIVATE_KEY).getFile());
        accountManagement.navigateTo();
        loginPage.form().login(user.getUsername(), "password");

        events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL_ERROR)
                .error(Errors.EMAIL_SEND_FAILED)
                .user(user.getId())
                .client("account")
                .detail(Details.USERNAME, "test-user@localhost")
                .detail(Details.EMAIL, "test-user@localhost")
                .removeDetail(Details.REDIRECT_URI)
                .assertEvent();

        // Email wasn't send
        Assert.assertNull(SslMailServer.getLastReceivedMessage());

        // Email wasn't send, but we won't notify end user about that. Admin is aware due to the error in the logs and the SEND_VERIFY_EMAIL_ERROR event.
        assertEquals("You need to verify your email address to activate your account.",
                testRealmVerifyEmailPage.feedbackMessage().getText());
    } finally {
        realmRep.getSmtpServer().put("host", "localhost");
        testRealm().update(realmRep);
    }
}
 
Example #24
Source File: FreeMarkerEmailTemplateProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected String toCamelCase(EventType event) {
    StringBuilder sb = new StringBuilder("event");
    for (String s : event.name().toLowerCase().split("_")) {
        sb.append(ObjectUtil.capitalize(s));
    }
    return sb.toString();
}
 
Example #25
Source File: AppInitiatedActionUpdateProfileTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
// This tests verifies that AIA still works if you call it after you are
// already logged in.  The other main difference between this and all other
// AIA tests is that the events are posted in a different order.
public void updateProfileLoginFirst() {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    
    doAIA();

    updateProfilePage.assertCurrent();

    updateProfilePage.update("New first", "New last", "[email protected]", "test-user@localhost");

    events.expectLogin().assertEvent();
    events.expectRequiredAction(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "[email protected]").assertEvent();
    events.expectRequiredAction(EventType.UPDATE_PROFILE).assertEvent();

    assertKcActionStatus("success");

    // assert user is really updated in persistent store
    UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost");
    Assert.assertEquals("New first", user.getFirstName());
    Assert.assertEquals("New last", user.getLastName());
    Assert.assertEquals("[email protected]", user.getEmail());
    Assert.assertEquals("test-user@localhost", user.getUsername());
}
 
Example #26
Source File: EventStoreProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void clear() {
    testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
    testing().onEvent(create(System.currentTimeMillis() - 20000, EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
    testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
    testing().onEvent(create(System.currentTimeMillis(), EventType.LOGIN, "realmId", "clientId", "userId", "127.0.0.1", "error"));
    testing().onEvent(create(System.currentTimeMillis() - 30000, EventType.LOGIN, "realmId2", "clientId", "userId", "127.0.0.1", "error"));

    testing().clearEventStore("realmId");

    Assert.assertEquals(1, testing().queryEvents(null, null, null, null, null, null, null, null, null).size());
}
 
Example #27
Source File: LoginEventsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultMaxResults() {
    RealmResource realm = adminClient.realms().realm("test");
    EventRepresentation event = new EventRepresentation();
    event.setRealmId(realm.toRepresentation().getId());
    event.setType(EventType.LOGIN.toString());

    for (int i = 0; i < 110; i++) {
        testingClient.testing("test").onEvent(event);
    }

    assertEquals(100, realm.getEvents(null, null, null, null, null, null, null, null).size());
    assertEquals(105, realm.getEvents(null, null, null, null, null, null, 0, 105).size());
    assertTrue(realm.getEvents(null, null, null, null, null, null, 0, 1000).size() >= 110);
}
 
Example #28
Source File: ImpersonationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Keycloak login(String username, String realm, ResteasyClient resteasyClient) {
    String clientId = establishClientId(realm);
    Keycloak client = createAdminClient(realm, clientId, username, null, resteasyClient);

    client.tokenManager().grantToken();
    // only poll for LOGIN event if realm is not master
    // - since for master testing event listener is not installed
    if (!AuthRealm.MASTER.equals(realm)) {
        EventRepresentation e = events.poll();
        Assert.assertEquals("Event type", EventType.LOGIN.toString(), e.getType());
        Assert.assertEquals("Client ID", clientId, e.getClientId());
        Assert.assertEquals("Username", username, e.getDetails().get("username"));
    }
    return client;
}
 
Example #29
Source File: SSOTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginWithRequiredActionAddedInTheMeantime() {
    // SSO login
    loginPage.open();
    loginPage.login("test-user@localhost", "password");

    assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
    Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));

    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();

    // Add update-profile required action to user now
    UserRepresentation user = testRealm().users().get(loginEvent.getUserId()).toRepresentation();
    user.getRequiredActions().add(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
    testRealm().users().get(loginEvent.getUserId()).update(user);

    // Attempt SSO login. update-password form is shown
    oauth.openLoginForm();
    updatePasswordPage.assertCurrent();

    updatePasswordPage.changePassword("password", "password");
    events.expectRequiredAction(EventType.UPDATE_PASSWORD).assertEvent();

    assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());

    loginEvent = events.expectLogin().removeDetail(Details.USERNAME).client("test-app").assertEvent();
    String sessionId2 = loginEvent.getSessionId();
    assertEquals(sessionId, sessionId2);


}
 
Example #30
Source File: ConsoleUpdatePassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    event.event(EventType.UPDATE_PASSWORD);
    String passwordNew = formData.getFirst(PASSWORD_NEW);
    String passwordConfirm = formData.getFirst(PASSWORD_CONFIRM);

    EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR)
            .client(context.getAuthenticationSession().getClient())
            .user(context.getAuthenticationSession().getAuthenticatedUser());

    if (Validation.isBlank(passwordNew)) {
        context.challenge(challenge(context).message(Messages.MISSING_PASSWORD));
        errorEvent.error(Errors.PASSWORD_MISSING);
        return;
    } else if (!passwordNew.equals(passwordConfirm)) {
        context.challenge(challenge(context).message(Messages.NOTMATCH_PASSWORD));
        errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
        return;
    }

    try {
        context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew, false));
        context.success();
    } catch (ModelException me) {
        errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
        context.challenge(challenge(context).text(me.getMessage()));
        return;
    } catch (Exception ape) {
        errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
        context.challenge(challenge(context).text(ape.getMessage()));
        return;
    }
}