org.keycloak.OAuth2Constants Java Examples

The following examples show how to use org.keycloak.OAuth2Constants. 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: X509DirectGrantTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void doResourceOwnerCredentialsLogin(String clientId, String clientSecret, String login, String password) throws Exception {

        oauth.clientId(clientId);
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(clientSecret, "", "", null);

        assertEquals(200, response.getStatusCode());

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

        AssertEvents.ExpectedEvent expectedEvent = events.expectLogin()
                .client(clientId)
                .user(userId)
                .session(accessToken.getSessionState())
                .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)
                .detail(Details.TOKEN_ID, accessToken.getId())
                .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
                .detail(Details.USERNAME, login)
                .removeDetail(Details.CODE_ID)
                .removeDetail(Details.REDIRECT_URI)
                .removeDetail(Details.CONSENT);

        addX509CertificateDetails(expectedEvent)
                .assertEvent();
    }
 
Example #2
Source File: OAuthScopeInTokenResponseTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void specifyEmptyScopeTest() throws Exception {
    String loginUser = "john-doh@localhost";
    String loginPassword = "password";
    String clientSecret = "password";
    
	String requestedScope = "";
	String expectedScope = "openid profile email";
	
	oauth.scope(requestedScope);
    oauth.doLogin(loginUser, loginPassword);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    
    expectSuccessfulResponseFromTokenEndpoint(code, expectedScope, clientSecret);
}
 
Example #3
Source File: SessionsPreloadCrossDCTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private List<OAuthClient.AccessTokenResponse> createInitialSessions(boolean offline) throws Exception {
    if (offline) {
        oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
    }

    List<OAuthClient.AccessTokenResponse> responses = new LinkedList<>();

    for (int i=0 ; i<SESSIONS_COUNT ; i++) {
        OAuthClient.AccessTokenResponse resp = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
        Assert.assertNull(resp.getError());
        Assert.assertNotNull(resp.getAccessToken());
        responses.add(resp);
    }

    return responses;
}
 
Example #4
Source File: LoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginInvalidUsername() {
    loginPage.open();
    loginPage.login("invalid", "password");

    loginPage.assertCurrent();

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

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

    events.expectLogin().user((String) null).session((String) null).error("user_not_found")
            .detail(Details.USERNAME, "invalid")
            .removeDetail(Details.CONSENT)
            .assertEvent();

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

    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 #5
Source File: JavascriptAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
// KEYCLOAK-4503
public void initializeWithRefreshToken() {

    oauth.setDriver(jsDriver); // Oauth need to login with jsDriver

    oauth.realm(REALM_NAME);
    oauth.clientId(CLIENT_ID);
    oauth.redirectUri(testAppUrl);
    oauth.doLogin(testUser);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String token = tokenResponse.getAccessToken();
    String refreshToken = tokenResponse.getRefreshToken();

    testExecutor.init(JSObjectBuilder.create()
                    .add("refreshToken", refreshToken)
            , (driver1, output, events) -> {
        assertInitNotAuth(driver1, output, events);
        waitUntilElement(events).text().not().contains("Auth Success");
    });
}
 
Example #6
Source File: OIDCJwksClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private OIDCClientRepresentation createClientWithManuallySetKid(String kid) throws Exception {
    OIDCClientRepresentation clientRep = createRep();

    clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS));
    clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT);

    // Generate keys for client
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.generateKeys("RS256");

    JSONWebKeySet keySet = oidcClientEndpointsResource.getJwks();

    // Override kid with custom value
    keySet.getKeys()[0].setKeyId(kid);
    clientRep.setJwks(keySet);

    return reg.oidc().create(clientRep);
}
 
Example #7
Source File: UserStorageOTPTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthentication() {
    // Test that user is required to provide OTP credential during authentication
    loginPage.open();
    loginPage.login("test-user", DummyUserFederationProvider.HARDCODED_PASSWORD);

    loginTotpPage.assertCurrent();

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

    loginTotpPage.login(DummyUserFederationProvider.HARDCODED_OTP);

    appPage.assertCurrent();
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
}
 
Example #8
Source File: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected void redirect(AuthenticationFlowContext context, String providerId) {

        IdentityProviderModel identityProviderModel = selectIdp(context, providerId);
        if (identityProviderModel == null || !identityProviderModel.isEnabled()) {
            log.warnf("Provider not found or not enabled for realm %s", providerId);
            context.attempted();
            return;
        }

        String accessCode = new ClientSessionCode<>(context.getSession(), context.getRealm(), context.getAuthenticationSession()).getOrGenerateCode();
        String clientId = context.getAuthenticationSession().getClient().getClientId();
        String tabId = context.getAuthenticationSession().getTabId();
        URI location = Urls.identityProviderAuthnRequest(context.getUriInfo().getBaseUri(), providerId, context.getRealm().getName(), accessCode, clientId, tabId);
        if (context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY) != null) {
            location = UriBuilder.fromUri(location).queryParam(OAuth2Constants.DISPLAY, context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY)).build();
        }
        log.debugf("Redirecting to %s", providerId);
        Response response = Response.seeOther(location).build();
        context.forceChallenge(response);
    }
 
Example #9
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void postLogoutWithValidIdTokenWhenLoggedOutByAdmin() throws Exception {
    oauth.doLogin("test-user@localhost", "password");

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

    oauth.clientSessionState("client-session");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String idTokenString = tokenResponse.getIdToken();

    adminClient.realm("test").logoutAll();

    // Logout should succeed with user already logged out, see KEYCLOAK-3399
    String logoutUrl = oauth.getLogoutUrl()
      .idTokenHint(idTokenString)
      .postLogoutRedirectUri(oauth.APP_AUTH_ROOT)
      .build();

    try (CloseableHttpClient c = HttpClientBuilder.create().disableRedirectHandling().build();
      CloseableHttpResponse response = c.execute(new HttpGet(logoutUrl))) {
        assertThat(response, Matchers.statusCodeIsHC(Status.FOUND));
        assertThat(response.getFirstHeader(HttpHeaders.LOCATION).getValue(), is(oauth.APP_AUTH_ROOT));
    }
}
 
Example #10
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected AuthChallenge checkStateCookie() {
    OIDCHttpFacade.Cookie stateCookie = getCookie(deployment.getStateCookieName());

    if (stateCookie == null) {
        log.warn("No state cookie");
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    // reset the cookie
    log.debug("** reseting application state cookie");
    facade.getResponse().resetCookie(deployment.getStateCookieName(), stateCookie.getPath());
    String stateCookieValue = getCookieValue(deployment.getStateCookieName());

    String state = getQueryParamValue(OAuth2Constants.STATE);
    if (state == null) {
        log.warn("state parameter was null");
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    if (!state.equals(stateCookieValue)) {
        log.warn("state parameter invalid");
        log.warn("cookie: " + stateCookieValue);
        log.warn("queryParam: " + state);
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    return null;

}
 
Example #11
Source File: JaxrsOAuthClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public String resolveBearerToken(String redirectUri, String code) {
    redirectUri = stripOauthParametersFromRedirect(redirectUri);
    Form codeForm = new Form()
            .param(OAuth2Constants.GRANT_TYPE, "authorization_code")
            .param(OAuth2Constants.CODE, code)
            .param(OAuth2Constants.CLIENT_ID, clientId)
            .param(OAuth2Constants.REDIRECT_URI, redirectUri);
    for (Map.Entry<String, Object> entry : credentials.entrySet()) {
        codeForm.param(entry.getKey(), (String) entry.getValue());
    }
    Response res = client.target(tokenUrl).request().post(Entity.form(codeForm));
    try {
        if (res.getStatus() == 400) {
            throw new BadRequestException();
        } else if (res.getStatus() != 200) {
            throw new InternalServerErrorException(new Exception("Unknown error when getting acess token"));
        }
        AccessTokenResponse tokenResponse = res.readEntity(AccessTokenResponse.class);
        return tokenResponse.getToken();
    } finally {
        res.close();
    }
}
 
Example #12
Source File: OIDCJwksClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createClientWithJWKSURI() throws Exception {
    OIDCClientRepresentation clientRep = createRep();

    clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS));
    clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT);

    // Generate keys for client
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    Map<String, String> generatedKeys = oidcClientEndpointsResource.generateKeys("RS256");

    clientRep.setJwksUri(TestApplicationResourceUrls.clientJwksUri());

    OIDCClientRepresentation response = reg.oidc().create(clientRep);
    Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod());
    Assert.assertNull(response.getClientSecret());
    Assert.assertNull(response.getClientSecretExpiresAt());
    Assert.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri());

    // Tries to authenticate client with privateKey JWT
    assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID);
}
 
Example #13
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected BrokeredIdentityContext exchangeExternalImpl(EventBuilder event, MultivaluedMap<String, String> params) {
    if (!supportsExternalExchange()) return null;
    String subjectToken = params.getFirst(OAuth2Constants.SUBJECT_TOKEN);
    if (subjectToken == null) {
        event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN + " param unset");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "token not set", Response.Status.BAD_REQUEST);
    }
    String subjectTokenType = params.getFirst(OAuth2Constants.SUBJECT_TOKEN_TYPE);
    if (subjectTokenType == null) {
        subjectTokenType = OAuth2Constants.ACCESS_TOKEN_TYPE;
    }
    if (OAuth2Constants.JWT_TOKEN_TYPE.equals(subjectTokenType) || OAuth2Constants.ID_TOKEN_TYPE.equals(subjectTokenType)) {
        return validateJwt(event, subjectToken, subjectTokenType);
    } else if (OAuth2Constants.ACCESS_TOKEN_TYPE.equals(subjectTokenType)) {
        return validateExternalTokenThroughUserInfo(event, subjectToken, subjectTokenType);
    } else {
        event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN_TYPE + " invalid");
        event.error(Errors.INVALID_TOKEN_TYPE);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token type", Response.Status.BAD_REQUEST);
    }
}
 
Example #14
Source File: X509BrowserLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginIgnoreX509IdentityContinueToFormLogin() throws Exception {
    // Set the X509 authenticator configuration
    AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig());
    String cfgId = createConfig(browserExecution.getId(), cfg);
    Assert.assertNotNull(cfgId);

    loginConfirmationPage.open();

    Assert.assertTrue(loginConfirmationPage.getSubjectDistinguishedNameText().startsWith("EMAILADDRESS=test-user@localhost"));
    Assert.assertEquals("test-user@localhost", loginConfirmationPage.getUsernameText());

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

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

     events.expectLogin()
             .user(userId)
             .detail(Details.USERNAME, "test-user@localhost")
             .removeDetail(Details.REDIRECT_URI)
             .assertEvent();
}
 
Example #15
Source File: X509BrowserLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginAttemptedNoConfig() {

    loginConfirmationPage.open();
    loginPage.assertCurrent();

    Assert.assertThat(loginPage.getInfoMessage(), containsString("X509 client authentication has not been configured yet"));
    // Continue with form based login
    loginPage.login("test-user@localhost", "password");

    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
    events.expectLogin()
            .user(userId)
            .detail(Details.USERNAME, "test-user@localhost")
            .removeDetail(Details.REDIRECT_URI)
            .assertEvent();
}
 
Example #16
Source File: MultiVersionClusterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void loginSuccessToLegacy() throws Exception {
    String originalServerRoot = OAuthClient.SERVER_ROOT;
    try {
        OAuthClient.updateURLs(legacyNode.getContextRoot().toString());
        OAuthClient oauth = new OAuthClient();
        oauth.init(DroneUtils.getCurrentDriver());
        oauth.realm(MASTER).clientId("account").redirectUri(legacyNode.getContextRoot().toString() + "/auth/realms/master/account/");
        
        oauth.openLoginForm();
        assertThat(DroneUtils.getCurrentDriver().getTitle(), containsString("Log in to "));
        loginPage.login("admin", "admin");

        assertThat("Login was not successful.", oauth.getCurrentQuery().get(OAuth2Constants.CODE), notNullValue());
    } finally {
        OAuthClient.updateURLs(originalServerRoot);
    }
}
 
Example #17
Source File: OAuthScopeInTokenResponseTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void specifyMultipleScopeTest() throws Exception {
    String loginUser = "[email protected]";
    String loginPassword = "password";
    String clientSecret = "password";
    
	String requestedScope = "address";
	String expectedScope = "openid profile email address";
	
	oauth.scope(requestedScope);
    oauth.doLogin(loginUser, loginPassword);

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    
    expectSuccessfulResponseFromTokenEndpoint(code, expectedScope, clientSecret);
}
 
Example #18
Source File: TokenIntrospectionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void testIntrospectAccessToken(String jwaAlgorithm) throws Exception {
    try {
        TokenSignatureUtil.changeClientAccessTokenSignatureProvider(ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"), jwaAlgorithm);

        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");

        assertEquals(jwaAlgorithm, new JWSInput(accessTokenResponse.getAccessToken()).getHeader().getAlgorithm().name());

        String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());

        TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);

        assertTrue(rep.isActive());
        assertEquals("test-user@localhost", rep.getUserName());
        assertEquals("test-app", rep.getClientId());
        assertEquals(loginEvent.getUserId(), rep.getSubject());

        // Assert expected scope
        OIDCScopeTest.assertScopes("openid email profile", rep.getScope());
    } finally {
        TokenSignatureUtil.changeClientAccessTokenSignatureProvider(ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"), Algorithm.RS256);
    }
}
 
Example #19
Source File: ResourceOwnerPasswordCredentialsGrantTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void grantAccessTokenUserNotFound() throws Exception {
    oauth.clientId("resource-owner");

    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "invalid", "invalid");

    assertEquals(401, response.getStatusCode());

    assertEquals("invalid_grant", response.getError());

    events.expectLogin()
            .client("resource-owner")
            .user((String) null)
            .session((String) null)
            .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)
            .detail(Details.USERNAME, "invalid")
            .removeDetail(Details.CODE_ID)
            .removeDetail(Details.REDIRECT_URI)
            .removeDetail(Details.CONSENT)
            .error(Errors.USER_NOT_FOUND)
            .assertEvent();
}
 
Example #20
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomClaimProvider() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only-with-cip.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();

    OIDCHttpFacade httpFacade = createHttpFacade("/api/resourcea", token);

    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    Permission permission = context.getPermissions().get(0);
    Map<String, Set<String>> claims = permission.getClaims();

    assertTrue(context.isGranted());
    assertEquals("test", claims.get("resolved-claim").iterator().next());
}
 
Example #21
Source File: AbstractKerberosTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected OAuthClient.AccessTokenResponse assertAuthenticationSuccess(String codeUrl) throws Exception {
    List<NameValuePair> pairs = URLEncodedUtils.parse(new URI(codeUrl), "UTF-8");
    String code = null;
    String state = null;
    for (NameValuePair pair : pairs) {
        if (pair.getName().equals(OAuth2Constants.CODE)) {
            code = pair.getValue();
        } else if (pair.getName().equals(OAuth2Constants.STATE)) {
            state = pair.getValue();
        }
    }
    Assert.assertNotNull(code);
    Assert.assertNotNull(state);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertNotNull(response.getAccessToken());
    events.clear();
    return response;
}
 
Example #22
Source File: LoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginSuccessRealmSigningAlgorithms() throws JWSInputException {
    ContainerAssume.assumeAuthServerSSL();

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

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

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

    driver.navigate().to(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test/");
    String keycloakIdentity = driver.manage().getCookieNamed("KEYCLOAK_IDENTITY").getValue();

    // Check identity cookie is signed with HS256
    String algorithm = new JWSInput(keycloakIdentity).getHeader().getAlgorithm().name();
    assertEquals("HS256", algorithm);

    try {
        TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.ES256);

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

        driver.navigate().to(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test/");
        keycloakIdentity = driver.manage().getCookieNamed("KEYCLOAK_IDENTITY").getValue();

        // Check identity cookie is still signed with HS256
        algorithm = new JWSInput(keycloakIdentity).getHeader().getAlgorithm().name();
        assertEquals("HS256", algorithm);

        // Check identity cookie still works
        oauth.openLoginForm();
        Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
    } finally {
        TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.RS256);
    }
}
 
Example #23
Source File: LoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginLoginHint() {
    String loginFormUrl = oauth.getLoginFormUrl() + "&login_hint=login-test";
    driver.navigate().to(loginFormUrl);

    Assert.assertEquals("login-test", loginPage.getUsername());
    loginPage.login("password");

    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 #24
Source File: X509BrowserLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginDuplicateUsersNotAllowed() {

    AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig());
    String cfgId = createConfig(browserExecution.getId(), cfg);
    Assert.assertNotNull(cfgId);

    // Set up the users so that the identity extracted from X509 client cert
    // matches more than a single user to trigger DuplicateModelException.

    UserRepresentation user = testRealm().users().get(userId2).toRepresentation();
    Assert.assertNotNull(user);

    user.singleAttribute("x509_certificate_identity", "Red Hat");
    this.updateUser(user);

    user = testRealm().users().get(userId).toRepresentation();
    Assert.assertNotNull(user);

    user.singleAttribute("x509_certificate_identity", "Red Hat");
    this.updateUser(user);

    events.clear();

    loginPage.open();

    Assert.assertThat(loginPage.getError(), containsString("X509 certificate authentication's failed."));

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

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

    events.expectLogin()
            .user(userId)
            .detail(Details.USERNAME, "test-user@localhost")
            .removeDetail(Details.REDIRECT_URI)
            .assertEvent();
}
 
Example #25
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void accessTokenUserSessionExpired() {
    oauth.doLogin("test-user@localhost", "password");

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

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


    testingClient.testing().removeUserSession("test", sessionId);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    assertEquals(400, tokenResponse.getStatusCode());
    assertNull(tokenResponse.getAccessToken());
    assertNull(tokenResponse.getRefreshToken());

    events.expectCodeToToken(codeId, sessionId)
            .removeDetail(Details.TOKEN_ID)
            .user((String) null)
            .removeDetail(Details.REFRESH_TOKEN_ID)
            .removeDetail(Details.REFRESH_TOKEN_TYPE)
            .error(Errors.INVALID_CODE).assertEvent();

    events.clear();
}
 
Example #26
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected JsonWebToken generateToken() {
    JsonWebToken jwt = new JsonWebToken();
    jwt.id(KeycloakModelUtils.generateId());
    jwt.type(OAuth2Constants.JWT);
    jwt.issuer(getConfig().getClientId());
    jwt.subject(getConfig().getClientId());
    jwt.audience(getConfig().getTokenUrl());
    int expirationDelay = session.getContext().getRealm().getAccessCodeLifespan();
    jwt.expiration(Time.currentTime() + expirationDelay);
    jwt.issuedNow();
    return jwt;
}
 
Example #27
Source File: TokenEndpointCorsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void accessTokenCorsRequest() throws Exception {
    oauth.realm("test");
    oauth.clientId("test-app2");
    oauth.redirectUri(VALID_CORS_URL + "/realms/master/app");

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

    // Token request
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    oauth.origin(VALID_CORS_URL);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    assertEquals(200, response.getStatusCode());
    assertCors(response);

    // Refresh request
    response = oauth.doRefreshTokenRequest(response.getRefreshToken(), null);

    assertEquals(200, response.getStatusCode());
    assertCors(response);

    // Invalid origin
    oauth.origin(INVALID_CORS_URL);
    response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "password");
    assertEquals(200, response.getStatusCode());
    assertNotCors(response);
    oauth.origin(VALID_CORS_URL);

    // No session
    oauth.openLogout();
    response = oauth.doRefreshTokenRequest(response.getRefreshToken(), null);
    assertEquals(400, response.getStatusCode());
    assertCors(response);
    assertEquals("invalid_grant", response.getError());
    assertEquals("Session not active", response.getErrorDescription());
}
 
Example #28
Source File: RealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void clientSessionStats() {
    setupTestAppAndUser();

    List<Map<String, String>> sessionStats = realm.getClientSessionStats();
    assertTrue(sessionStats.isEmpty());

    System.out.println(sessionStats.size());

    oauth.doLogin("testuser", "password");
    AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE),
        "secret");
    assertEquals(200, tokenResponse.getStatusCode());

    sessionStats = realm.getClientSessionStats();

    assertEquals(1, sessionStats.size());
    assertEquals("test-app", sessionStats.get(0).get("clientId"));
    assertEquals("1", sessionStats.get(0).get("active"));

    String clientUuid = sessionStats.get(0).get("id");
    realm.clients().get(clientUuid).remove();

    sessionStats = realm.getClientSessionStats();

    assertEquals(0, sessionStats.size());
}
 
Example #29
Source File: RefreshTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void refreshTokenAfterUserLogoutAndLoginAgain() {
    String refreshToken1 = loginAndForceNewLoginPage();

    oauth.doLogout(refreshToken1, "password");
    events.clear();

    // Set time offset to 2 (Just to simulate to be more close to real situation)
    setTimeOffset(2);

    // Continue with login
    oauth.fillLoginForm("test-user@localhost", "password");

    assertFalse(loginPage.isCurrent());

    OAuthClient.AccessTokenResponse tokenResponse2 = null;
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    tokenResponse2 = oauth.doAccessTokenRequest(code, "password");

    setTimeOffset(4);
    // Now try refresh with the original refreshToken1 created in logged-out userSession. It should fail
    OAuthClient.AccessTokenResponse responseReuseExceeded = oauth.doRefreshTokenRequest(refreshToken1, "password");
    assertEquals(400, responseReuseExceeded.getStatusCode());

    setTimeOffset(6);
    // Finally try with valid refresh token
    responseReuseExceeded = oauth.doRefreshTokenRequest(tokenResponse2.getRefreshToken(), "password");
    assertEquals(200, responseReuseExceeded.getStatusCode());
}
 
Example #30
Source File: TokenIntrospectionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntrospectRefreshTokenAfterUserSessionLogoutAndLoginAgain() throws Exception {
    AccessTokenResponse accessTokenResponse = loginAndForceNewLoginPage();
    String refreshToken1 = accessTokenResponse.getRefreshToken();

    oauth.doLogout(refreshToken1, "password");
    events.clear();

    setTimeOffset(2);

    oauth.fillLoginForm("test-user@localhost", "password");
    events.expectLogin().assertEvent();

    Assert.assertFalse(loginPage.isCurrent());

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

    String introspectResponse = oauth.introspectRefreshTokenWithClientCredential("confidential-cli", "secret1", tokenResponse2.getRefreshToken());

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(introspectResponse);
    assertTrue(jsonNode.get("active").asBoolean());

    introspectResponse = oauth.introspectRefreshTokenWithClientCredential("confidential-cli", "secret1", refreshToken1);

    jsonNode = objectMapper.readTree(introspectResponse);
    assertFalse(jsonNode.get("active").asBoolean());
}