org.keycloak.events.Details Java Examples

The following examples show how to use org.keycloak.events.Details. 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: AbstractKerberosTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected AccessToken assertSuccessfulSpnegoLogin(String clientId, String loginUsername, String expectedUsername, String password) throws Exception {
    oauth.clientId(clientId);
    Response spnegoResponse = spnegoLogin(loginUsername, password);
    Assert.assertEquals(302, spnegoResponse.getStatus());

    List<UserRepresentation> users = testRealmResource().users().search(expectedUsername, 0, 1);
    String userId = users.get(0).getId();
    events.expectLogin()
            .client(clientId)
            .user(userId)
            .detail(Details.USERNAME, expectedUsername)
            .assertEvent();

    String codeUrl = spnegoResponse.getLocation().toString();

    OAuthClient.AccessTokenResponse tokenResponse = assertAuthenticationSuccess(codeUrl);

    AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
    Assert.assertEquals(userId, token.getSubject());
    Assert.assertEquals(expectedUsername, token.getPreferredUsername());

    return token;
}
 
Example #2
Source File: OAuthProofKeyForCodeExchangeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void accessTokenRequestValidS256CodeChallengeMethodPkceEnforced() throws Exception {
    try {
        setPkceActivationSettings("test-app", OAuth2Constants.PKCE_METHOD_S256);
        String codeVerifier = "1a345A7890123456r8901c3456789012b45K7890l23"; // 43
        String codeChallenge = generateS256CodeChallenge(codeVerifier);
        oauth.codeChallenge(codeChallenge);
        oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);

        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        oauth.codeVerifier(codeVerifier);

        expectSuccessfulResponseFromTokenEndpoint(codeId, sessionId, code);
    } finally {
        setPkceActivationSettings("test-app", null);
    }
}
 
Example #3
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public Response authenticateOnly() throws AuthenticationFlowException {
    logger.debug("AUTHENTICATE ONLY");
    checkClientSession(false);
    event.client(authenticationSession.getClient().getClientId())
            .detail(Details.REDIRECT_URI, authenticationSession.getRedirectUri())
            .detail(Details.AUTH_METHOD, authenticationSession.getProtocol());
    String authType = authenticationSession.getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        event.detail(Details.AUTH_TYPE, authType);
    }
    UserModel authUser = authenticationSession.getAuthenticatedUser();
    validateUser(authUser);
    AuthenticationFlow authenticationFlow = createFlowExecution(this.flowId, null);
    Response challenge = authenticationFlow.processFlow();
    if (challenge != null) return challenge;
    if (authenticationSession.getAuthenticatedUser() == null) {
        throw new AuthenticationFlowException(AuthenticationFlowError.UNKNOWN_USER);
    }
    if (!authenticationFlow.isSuccessful()) {
        throw new AuthenticationFlowException(authenticationFlow.getFlowExceptions());
    }
    return null;
}
 
Example #4
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response exchangeStoredToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(tokenSubject, getConfig().getAlias(), authorizedClient.getRealm());
    if (model == null || model.getToken() == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeNotLinked(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    String accessToken = extractTokenFromResponse(model.getToken(), getAccessTokenResponseParameter());
    if (accessToken == null) {
        model.setToken(null);
        session.users().updateFederatedIdentity(authorizedClient.getRealm(), tokenSubject, model);
        event.detail(Details.REASON, "requested_issuer token expired");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    AccessTokenResponse tokenResponse = new AccessTokenResponse();
    tokenResponse.setToken(accessToken);
    tokenResponse.setIdToken(null);
    tokenResponse.setRefreshToken(null);
    tokenResponse.setRefreshExpiresIn(0);
    tokenResponse.getOtherClaims().clear();
    tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    event.success();
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example #5
Source File: LoginTotpTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginWithTotpFailure() throws Exception {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");

    Assert.assertTrue(loginTotpPage.isCurrent());

    loginTotpPage.login("123456");
    loginTotpPage.assertCurrent();
    Assert.assertEquals("Invalid authenticator code.", loginPage.getError());

    //loginPage.assertCurrent();  // Invalid authenticator code.
    //Assert.assertEquals("Invalid username or password.", loginPage.getError());

    events.expectLogin().error("invalid_user_credentials").session((String) null)
            .removeDetail(Details.CONSENT)
            .assertEvent();
}
 
Example #6
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void promptLoginDifferentUser() throws Exception {
    String sss = oauth.getLoginFormUrl();
    System.out.println(sss);

    // Login user
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent);

    // Assert need to re-authenticate with prompt=login
    driver.navigate().to(oauth.getLoginFormUrl() + "&prompt=login");

    // Authenticate as different user
    loginPage.assertCurrent();
    loginPage.login("john-doh@localhost", "password");

    errorPage.assertCurrent();
    Assert.assertTrue(errorPage.getError().startsWith("You are already authenticated as different user"));
}
 
Example #7
Source File: LoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginInvalidPasswordDisabledUser() {
    setUserEnabled("login-test", false);

    try {
        loginPage.open();
        loginPage.login("login-test", "invalid");

        loginPage.assertCurrent();

        // KEYCLOAK-1741 - assert form field values kept
        Assert.assertEquals("login-test", loginPage.getUsername());
        Assert.assertEquals("", loginPage.getPassword());

        // KEYCLOAK-2024
        Assert.assertEquals("Invalid username or password.", loginPage.getError());

        events.expectLogin().user(userId).session((String) null).error("invalid_user_credentials")
                .detail(Details.USERNAME, "login-test")
                .removeDetail(Details.CONSENT)
                .assertEvent();
    } finally {
        setUserEnabled("login-test", true);
    }
}
 
Example #8
Source File: BrowserFlowTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@AuthServerContainerExclude(REMOTE)
public void testConditionalFlowWithConditionalAuthenticatorEvaluatingToTrueActsAsRequired(){
    String newFlowAlias = "browser - copy 1";
    configureBrowserFlowWithConditionalFlowWithOTP(newFlowAlias);

    try {
        loginUsernameOnlyPage.open();
        loginUsernameOnlyPage.assertCurrent();
        loginUsernameOnlyPage.login("user-with-one-configured-otp");

        // Assert on password page now
        Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent());
        loginTotpPage.assertCurrent();
        loginTotpPage.assertOtpCredentialSelectorAvailability(false);

        loginTotpPage.login(getOtpCode(USER_WITH_ONE_OTP_OTP_SECRET));
        Assert.assertFalse(loginTotpPage.isCurrent());
        events.expectLogin().user(testRealm().users().search("user-with-one-configured-otp").get(0).getId())
                .detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent();

    } finally {
        revertFlows("browser - copy 1");
    }
}
 
Example #9
Source File: AuthorizationCodeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void authorizationRequestFormPostResponseModeWithCustomState() throws IOException {
    oauth.responseMode(OIDCResponseMode.FORM_POST.toString().toLowerCase());
    oauth.stateParamHardcoded("\"><foo>bar_baz(2)far</foo>");
    oauth.doLoginGrant("test-user@localhost", "password");

    String sources = driver.getPageSource();
    System.out.println(sources);

    String code = driver.findElement(By.id("code")).getText();
    String state = driver.findElement(By.id("state")).getText();

    assertEquals("\"><foo>bar_baz(2)far</foo>", state);

    String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID);
}
 
Example #10
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertSuccess(OAuthClient.AccessTokenResponse response, String clientId, String userId, String userName) {
    assertEquals(200, response.getStatusCode());

    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());

    events.expectClientLogin()
            .client(clientId)
            .user(userId)
            .session(accessToken.getSessionState())
            .detail(Details.TOKEN_ID, accessToken.getId())
            .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
            .detail(Details.USERNAME, userName)
            .detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID)
            .assertEvent();
}
 
Example #11
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void logoutIDTokenHint() {
    oauth.doLogin("test-user@localhost", "password");

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

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

    events.clear();

    driver.navigate().to(oauth.getLogoutUrl().redirectUri(oauth.APP_AUTH_ROOT).idTokenHint(idToken).build());
    events.expectLogout(sessionId).detail(Details.REDIRECT_URI, oauth.APP_AUTH_ROOT).assertEvent();

    assertCurrentUrlEquals(oauth.APP_AUTH_ROOT);
}
 
Example #12
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 #13
Source File: OIDCHybridResponseTypeCodeIDTokenTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected List<IDToken> testAuthzResponseAndRetrieveIDTokens(OAuthClient.AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) {
    Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE));

    // IDToken from the authorization response
    Assert.assertNotNull(authzResponse.getAccessToken());
    String idTokenStr = authzResponse.getIdToken();
    IDToken idToken = oauth.verifyIDToken(idTokenStr);

    // Validate "at_hash"
    assertValidAccessTokenHash(idToken.getAccessTokenHash(), authzResponse.getAccessToken());

    // Validate "c_hash"
    assertValidCodeHash(idToken.getCodeHash(), authzResponse.getCode());

    // Financial API - Part 2: Read and Write API Security Profile
    // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server
    // Validate "s_hash"
    Assert.assertNotNull(idToken.getStateHash());

    Assert.assertEquals(idToken.getStateHash(), HashUtils.oidcHash(getIdTokenSignatureAlgorithm(), authzResponse.getState()));

    // IDToken exchanged for the code
    IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent);

    return Arrays.asList(idToken, idToken2);
}
 
Example #14
Source File: AccountFormServiceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void changePasswordWithSpecialCharsPolicy() {
    setPasswordPolicy("specialChars(2)");

    changePasswordPage.open();
    loginPage.login("test-user@localhost", "password");
    events.expectLogin().client("account").detail(Details.REDIRECT_URI, getAccountRedirectUrl() + "?path=password").assertEvent();

    changePasswordPage.changePassword("password", "invalidPassword*", "invalidPassword*");
    Assert.assertEquals("Invalid password: must contain at least 2 special characters.", profilePage.getError());
    events.expectAccount(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_REJECTED).assertEvent();


    changePasswordPage.changePassword("password", "validPassword*#", "validPassword*#");
    Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
    events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();
}
 
Example #15
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
	context.getEvent().detail(Details.AUTH_METHOD, "auth_method");
	if (logger.isInfoEnabled()) {
		logger.info(
				"validateRecaptcha(AuthenticationFlowContext, boolean, String, String) - Before the validation");
	}

	AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
	LoginFormsProvider form = context.form();
	String userLanguageTag = context.getSession().getContext().resolveLocale(context.getUser()).toLanguageTag();

	if (captchaConfig == null || captchaConfig.getConfig() == null
			|| captchaConfig.getConfig().get(SITE_KEY) == null
			|| captchaConfig.getConfig().get(SITE_SECRET) == null) {
		form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED));
		return;
	}
	siteKey = captchaConfig.getConfig().get(SITE_KEY);
	form.setAttribute("recaptchaRequired", true);
	form.setAttribute("recaptchaSiteKey", siteKey);
	form.addScript("https://www.google.com/recaptcha/api.js?hl=" + userLanguageTag);

	super.authenticate(context);
}
 
Example #16
Source File: AssertEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ExpectedEvent expectCodeToToken(String codeId, String sessionId) {
    return expect(EventType.CODE_TO_TOKEN)
            .detail(Details.CODE_ID, codeId)
            .detail(Details.TOKEN_ID, isUUID())
            .detail(Details.REFRESH_TOKEN_ID, isUUID())
            .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_REFRESH)
            .detail(Details.CLIENT_AUTH_METHOD, ClientIdAndSecretAuthenticator.PROVIDER_ID)
            .session(sessionId);
}
 
Example #17
Source File: UserTotpTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void setupTotp() {
    totpPage.open();
    loginPage.login("test-user@localhost", "password");

    events.expectLogin().client("account").detail(Details.REDIRECT_URI, getAccountRedirectUrl() + "?path=totp").assertEvent();

    Assert.assertTrue(totpPage.isCurrent());

    Assert.assertFalse(driver.getPageSource().contains("Remove Google"));

    totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()));

    Assert.assertEquals("Mobile authenticator configured.", profilePage.getSuccess());

    events.expectAccount(EventType.UPDATE_TOTP).assertEvent();

    Assert.assertTrue(driver.getPageSource().contains("pficon-delete"));

    List<UserRepresentation> users = adminClient.realms().realm("test").users().search("test-user@localhost", null, null, null, 0, 1);
    String userId = users.get(0).getId();
    testingClient.testing().clearAdminEventQueue();
    CredentialRepresentation totpCredential = adminClient.realms().realm("test").users().get(userId).credentials()
            .stream().filter(c -> OTPCredentialModel.TYPE.equals(c.getType())).findFirst().get();
    adminClient.realms().realm("test").users().get(userId).removeCredential(totpCredential.getId());

    totpPage.open();
    Assert.assertFalse(driver.getPageSource().contains("pficon-delete"));

    AdminEventRepresentation event = testingClient.testing().pollAdminEvent();
    Assert.assertNotNull(event);
    Assert.assertEquals(OperationType.ACTION.name(), event.getOperationType());
    Assert.assertEquals("users/" + userId + "/credentials/" + totpCredential.getId(), event.getResourcePath());
}
 
Example #18
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response checkAccountManagementFailedLinking(AuthenticationSessionModel authSession, String error, Object... parameters) {
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authSession);
    if (userSession != null && authSession.getClient() != null && authSession.getClient().getClientId().equals(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID)) {

        this.event.event(EventType.FEDERATED_IDENTITY_LINK);
        UserModel user = userSession.getUser();
        this.event.user(user);
        this.event.detail(Details.USERNAME, user.getUsername());

        return redirectToAccountErrorPage(authSession, error, parameters);
    } else {
        return null;
    }
}
 
Example #19
Source File: CustomFlowTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginSuccess() {
    AuthenticatorState state = new AuthenticatorState();
    state.setUsername("login-test");
    state.setClientId("test-app");
    testingClient.testing().updateAuthenticator(state);

    oauth.openLoginForm();

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

    events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent();
}
 
Example #20
Source File: OAuthProofKeyForCodeExchangeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void accessTokenRequestInPKCEInvalidOverCodeVerifierWithS256CodeChallengeMethod() throws Exception {
	// test case : success : A-1-11
	String codeVerifier = "3fRc92kac_keic8c7al-3ncbdoaie.DDeizlck3~3fRc92kac_keic8c7al-3ncbdoaie.DDeizlck3~3fRc92kac_keic8c7al-3ncbdoaie.DDeizlck3~123456789"; // 129
	String codeChallenge = generateS256CodeChallenge(codeVerifier);
	oauth.codeChallenge(codeChallenge);
	oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_S256);
	
    oauth.doLogin("test-user@localhost", "password");

    EventRepresentation loginEvent = events.expectLogin().assertEvent();

    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    oauth.codeVerifier(codeVerifier);
    
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    
    assertEquals(400, response.getStatusCode());
    assertEquals(OAuthErrorException.INVALID_GRANT, response.getError());
    assertEquals("PKCE invalid code verifier", response.getErrorDescription());
    
    events.expectCodeToToken(codeId, sessionId).error(Errors.INVALID_CODE_VERIFIER).clearDetails().assertEvent();
}
 
Example #21
Source File: RequiredActionEmailVerificationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyEmailExisting() throws IOException, MessagingException {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");

    verifyEmailPage.assertCurrent();

    Assert.assertEquals(1, greenMail.getReceivedMessages().length);

    MimeMessage message = greenMail.getReceivedMessages()[0];

    String verificationUrl = getPasswordResetEmailLink(message);

    AssertEvents.ExpectedEvent emailEvent = events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL).detail("email", "test-user@localhost");
    EventRepresentation sendEvent = emailEvent.assertEvent();
    String mailCodeId = sendEvent.getDetails().get(Details.CODE_ID);

    driver.navigate().to(verificationUrl.trim());

    events.expectRequiredAction(EventType.VERIFY_EMAIL)
      .user(testUserId)
      .detail(Details.USERNAME, "test-user@localhost")
      .detail(Details.EMAIL, "test-user@localhost")
      .detail(Details.CODE_ID, mailCodeId)
      .assertEvent();

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

    events.expectLogin().user(testUserId).session(mailCodeId).detail(Details.USERNAME, "test-user@localhost").assertEvent();
}
 
Example #22
Source File: RefreshTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void refreshTokenUserDeleted() throws Exception {
    String userId = createUser("test", "temp-user@localhost", "password");
    oauth.doLogin("temp-user@localhost", "password");

    EventRepresentation loginEvent = events.expectLogin().user(userId).assertEvent();

    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    String refreshTokenString = response.getRefreshToken();
    RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);

    events.expectCodeToToken(codeId, sessionId).user(userId).assertEvent();

    adminClient.realm("test").users().delete(userId);

    setTimeOffset(2);
    response = oauth.doRefreshTokenRequest(refreshTokenString, "password");
    assertEquals(400, response.getStatusCode());
    assertEquals("invalid_grant", response.getError());

    events.expectRefresh(refreshToken.getId(), sessionId).user(userId).clearDetails().error(Errors.INVALID_TOKEN).assertEvent();
}
 
Example #23
Source File: SessionCodeChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response restartAuthenticationSessionFromCookie(RootAuthenticationSessionModel existingRootSession) {
    logger.debug("Authentication session not found. Trying to restart from cookie.");
    AuthenticationSessionModel authSession = null;

    try {
        authSession = RestartLoginCookie.restartSession(session, realm, existingRootSession, clientId);
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToParseRestartLoginCookie(e);
    }

    if (authSession != null) {

        event.clone();
        event.detail(Details.RESTART_AFTER_TIMEOUT, "true");
        event.error(Errors.EXPIRED_CODE);

        String warningMessage = Messages.LOGIN_TIMEOUT;
        authSession.setAuthNote(LoginActionsService.FORWARDED_ERROR_MESSAGE_NOTE, warningMessage);

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

        URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getTabId());
        logger.debugf("Authentication session restart from cookie succeeded. Redirecting to %s", redirectUri);
        return Response.status(Response.Status.FOUND).location(redirectUri).build();
    } else {
        // Finally need to show error as all the fallbacks failed
        event.error(Errors.INVALID_CODE);
        return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
    }
}
 
Example #24
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void testCodeToTokenRequestSuccess(String algorithm) throws Exception {
    ClientRepresentation clientRepresentation = app2;
    ClientResource clientResource = getClient(testRealm.getRealm(), clientRepresentation.getId());
    clientRepresentation = clientResource.toRepresentation();
    try {
        // setup Jwks
        KeyPair keyPair = setupJwks(algorithm, clientRepresentation, clientResource);
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // test
        oauth.clientId("client2");
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin()
                .client("client2")
                .assertEvent();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = doAccessTokenRequest(code, createSignedRequestToken("client2", getRealmInfoUrl(), privateKey, publicKey, algorithm));

        assertEquals(200, response.getStatusCode());
        oauth.verifyToken(response.getAccessToken());
        oauth.parseRefreshToken(response.getRefreshToken());
        events.expectCodeToToken(loginEvent.getDetails().get(Details.CODE_ID), loginEvent.getSessionId())
                .client("client2")
                .detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID)
                .assertEvent();
    } finally {
        // Revert jwks_url settings
        revertJwksSettings(clientRepresentation, clientResource);
    }
}
 
Example #25
Source File: OfflineTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testShortOfflineSessionMax() throws Exception {
    int prevOfflineSession[] = null;
    int prevSession[] = null;
    try {
        prevOfflineSession = changeOfflineSessionSettings(true, 60, 30);
        prevSession = changeSessionSettings(1800, 300);

        oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
        oauth.clientId("offline-client");
        oauth.redirectUri(offlineClientAppUri);
        oauth.doLogin("test-user@localhost", "password");

        events.expectLogin().client("offline-client").detail(Details.REDIRECT_URI, offlineClientAppUri).assertEvent();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "secret1");
        String offlineTokenString = tokenResponse.getRefreshToken();
        RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);

        Assert.assertThat(tokenResponse.getExpiresIn(), allOf(greaterThanOrEqualTo(59), lessThanOrEqualTo(60)));
        Assert.assertThat(tokenResponse.getRefreshExpiresIn(), allOf(greaterThanOrEqualTo(29), lessThanOrEqualTo(30)));
        assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType());

        String introspectionResponse = oauth.introspectAccessTokenWithClientCredential("test-app", "password",
            tokenResponse.getAccessToken());
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(introspectionResponse);
        Assert.assertEquals(true, jsonNode.get("active").asBoolean());
        Assert.assertEquals("test-user@localhost", jsonNode.get("email").asText());
        Assert.assertThat(jsonNode.get("exp").asInt() - getCurrentTime(),
            allOf(greaterThanOrEqualTo(59), lessThanOrEqualTo(60)));

    } finally {
        changeOfflineSessionSettings(false, prevOfflineSession[0], prevOfflineSession[1]);
        changeSessionSettings(prevSession[0], prevSession[1]);
    }
}
 
Example #26
Source File: ClientsManagementService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * URL invoked by adapter to register new client cluster node. Each application cluster node will invoke this URL once it joins cluster
 *
 * @param authorizationHeader
 * @param formData
 * @return
 */
@Path("unregister-node")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response unregisterNode(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, final MultivaluedMap<String, String> formData) {
    if (!checkSsl()) {
        throw new ForbiddenException("HTTPS required");
    }

    event.event(EventType.UNREGISTER_NODE);

    if (!realm.isEnabled()) {
        event.error(Errors.REALM_DISABLED);
        throw new NotAuthorizedException("Realm not enabled");
    }

    ClientModel client = authorizeClient();
    String nodeHost = getClientClusterHost(formData);

    event.client(client).detail(Details.NODE_HOST, nodeHost);
    logger.debugf("Unregistering cluster host '%s' for client '%s'", nodeHost, client.getClientId());

    client.unregisterNode(nodeHost);

    event.success();

    return Response.noContent().build();
}
 
Example #27
Source File: OAuthProofKeyForCodeExchangeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void accessTokenRequestWithoutPKCE() throws Exception {
	// test case : success : A-1-1
    oauth.doLogin("test-user@localhost", "password");

    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    
    expectSuccessfulResponseFromTokenEndpoint(codeId, sessionId, code);
}
 
Example #28
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void accessTokenInvalidClientCredentials() throws Exception {
    oauth.doLogin("test-user@localhost", "password");

    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "invalid");
    assertEquals(401, response.getStatusCode());

    AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_client_credentials").clearDetails().user((String) null).session((String) null);
    expectedEvent.assertEvent();
}
 
Example #29
Source File: LoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginWithForcePasswordChangePolicy() {
    setPasswordPolicy("forceExpiredPasswordChange(1)");

    try {
        // Setting offset to more than one day to force password update
        // elapsedTime > timeToExpire
        setTimeOffset(86405);

        loginPage.open();

        loginPage.login("login-test", "password");

        updatePasswordPage.assertCurrent();

        updatePasswordPage.changePassword("updatedPassword", "updatedPassword");

        setTimeOffset(0);

        events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, "login-test").assertEvent();

        String currentUrl = driver.getCurrentUrl();
        String pageSource = driver.getPageSource();
        assertEquals("bad expectation, on page: " + currentUrl, RequestType.AUTH_RESPONSE, appPage.getRequestType());

        events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent();

    } finally {
        setPasswordPolicy(null);
        UserResource userRsc = adminClient.realm("test").users().get("login-test");
        ApiUtil.resetUserPassword(userRsc, "password", false);
    }
}
 
Example #30
Source File: AccountFormServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void changePassword() {
    changePasswordPage.open();
    loginPage.login("test-user@localhost", "password");

    EventRepresentation event = events.expectLogin().client("account").detail(Details.REDIRECT_URI, getAccountRedirectUrl() + "?path=password").assertEvent();
    String sessionId = event.getSessionId();
    String userId = event.getUserId();

    changePasswordPage.changePassword("", "new-password", "new-password");
    Assert.assertEquals("Please specify password.", profilePage.getError());
    events.expectAccount(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_MISSING).assertEvent();

    changePasswordPage.changePassword("password", "new-password", "new-password2");
    Assert.assertEquals("Password confirmation doesn't match.", profilePage.getError());
    events.expectAccount(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_CONFIRM_ERROR).assertEvent();

    changePasswordPage.changePassword("password", "new-password", "new-password");
    Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
    events.expectAccount(EventType.UPDATE_PASSWORD).assertEvent();

    changePasswordPage.logout();
    events.expectLogout(sessionId).detail(Details.REDIRECT_URI, changePasswordPage.getPath()).assertEvent();

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

    Assert.assertEquals("Invalid username or password.", loginPage.getError());

    events.expectLogin().session((String) null).error(Errors.INVALID_USER_CREDENTIALS)
            .removeDetail(Details.CONSENT)
            .assertEvent();

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

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

    events.expectLogin().assertEvent();
}