Search in sources :

Example 11 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class CamelHelloProcessor method process.

@Override
public void process(Exchange exchange) throws Exception {
    // Fuse 7
    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) exchange.getProperty(KeycloakPrincipal.class.getName(), KeycloakPrincipal.class);
    if (keycloakPrincipal == null) {
        // Fuse 6.3
        HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
        keycloakPrincipal = (KeycloakPrincipal) req.getUserPrincipal();
    }
    AccessToken accessToken = keycloakPrincipal.getKeycloakSecurityContext().getToken();
    String username = accessToken.getPreferredUsername();
    String fullName = accessToken.getName();
    exchange.getOut().setBody("Hello " + username + "! Your full name is " + fullName + ".");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessToken(org.keycloak.representations.AccessToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 12 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testExternalExchange_extractIdentityFromProfile.

/**
 * KEYCLOAK-14577, see also KEYCLOAK-10932
 */
@Test
public void testExternalExchange_extractIdentityFromProfile() throws Exception {
    RealmResource childRealm = adminClient.realms().realm(CHILD_IDP);
    String accessToken = oauth.doGrantAccessTokenRequest(PARENT_IDP, PARENT3_USERNAME, "password", null, PARENT_CLIENT, "password").getAccessToken();
    Assert.assertEquals(0, adminClient.realm(CHILD_IDP).getClientSessionStats().size());
    Client httpClient = AdminClientUtil.createResteasyClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        IdentityProviderRepresentation rep = adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).toRepresentation();
        rep.getConfig().put(OIDCIdentityProviderConfig.VALIDATE_SIGNATURE, String.valueOf(false));
        adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).update(rep);
        AccessToken token;
        try (Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.JWT_TOKEN_TYPE).param(OAuth2Constants.SUBJECT_ISSUER, PARENT_IDP).param(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID)))) {
            Assert.assertEquals(200, response.getStatus());
            AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
            JWSInput jws = new JWSInput(tokenResponse.getToken());
            token = jws.readJsonContent(AccessToken.class);
        }
        Assert.assertNotNull(token);
        Assert.assertNotNull(token.getSubject());
        Assert.assertEquals(PARENT3_USERNAME, token.getPreferredUsername());
        Assert.assertEquals("first name", token.getGivenName());
        Assert.assertEquals("last name", token.getFamilyName());
        Assert.assertEquals("email", token.getEmail());
        // cleanup remove the user
        childRealm.users().get(token.getSubject()).remove();
    } finally {
        httpClient.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) RealmResource(org.keycloak.admin.client.resource.RealmResource) AccessToken(org.keycloak.representations.AccessToken) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) WebTarget(javax.ws.rs.client.WebTarget) JWSInput(org.keycloak.jose.jws.JWSInput) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 13 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class DemoServletsAdapterTest method testOIDCParamsForwarding.

// Tests forwarding of parameters like "prompt"
@Test
public void testOIDCParamsForwarding() {
    // test login to customer-portal which does a bearer request to customer-db
    securePortal.navigateTo();
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("bburke@redhat.com", "password");
    waitForPageToLoad();
    assertCurrentUrlStartsWith(securePortal);
    assertLogged();
    int currentTime = Time.currentTime();
    try {
        setAdapterAndServerTimeOffset(10, securePortal.toString());
        // Test I need to reauthenticate with prompt=login
        String appUri = tokenMinTTLPage.getUriBuilder().queryParam(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN).build().toString();
        URLUtils.navigateToUri(appUri);
        assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
        WaitUtils.waitForPageToLoad();
        testRealmLoginPage.form().setPassword("password");
        testRealmLoginPage.form().login();
        AccessToken token = tokenMinTTLPage.getAccessToken();
        int authTime = token.getAuthTime();
        assertThat(authTime, is(greaterThanOrEqualTo(currentTime + 10)));
    } finally {
        setAdapterAndServerTimeOffset(0, securePortal.toString());
    }
}
Also used : InputPortalNoAccessToken(org.keycloak.testsuite.adapter.page.InputPortalNoAccessToken) AccessToken(org.keycloak.representations.AccessToken) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 14 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class DemoServletsAdapterTest method testTokenMinTTL.

// Tests "token-minimum-time-to-live" adapter configuration option
@Test
public void testTokenMinTTL() {
    // Login
    tokenMinTTLPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("bburke@redhat.com", "password");
    assertCurrentUrlEquals(tokenMinTTLPage);
    // Get time of token
    AccessToken token = tokenMinTTLPage.getAccessToken();
    int tokenIssued1 = token.getIssuedAt();
    // Sets 5 minutes offset and assert access token will be still the same
    setAdapterAndServerTimeOffset(300, tokenMinTTLPage.toString());
    tokenMinTTLPage.navigateTo();
    token = tokenMinTTLPage.getAccessToken();
    int tokenIssued2 = token.getIssuedAt();
    Assert.assertEquals(tokenIssued1, tokenIssued2);
    assertFalse(token.isExpired());
    // Sets 9 minutes offset and assert access token will be refreshed (accessTokenTimeout is 10 minutes, token-min-ttl is 2 minutes. Hence 8 minutes or more should be sufficient)
    setAdapterAndServerTimeOffset(540, tokenMinTTLPage.toString());
    tokenMinTTLPage.navigateTo();
    token = tokenMinTTLPage.getAccessToken();
    int tokenIssued3 = token.getIssuedAt();
    Assert.assertTrue(tokenIssued3 > tokenIssued1);
    // Revert times
    setAdapterAndServerTimeOffset(0, tokenMinTTLPage.toString());
}
Also used : InputPortalNoAccessToken(org.keycloak.testsuite.adapter.page.InputPortalNoAccessToken) AccessToken(org.keycloak.representations.AccessToken) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 15 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class CIBATest method testDuplicatedTokenRequestWithSameAuthReqId.

@Test
public void testDuplicatedTokenRequestWithSameAuthReqId() throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        final String username = "nutzername-gelb";
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        assertThat(clientResource, notNullValue());
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep);
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, "kciwje86");
        // user Authentication Channel Request
        TestAuthenticationChannelRequest authenticationChannelReq = doAuthenticationChannelRequest("kciwje86");
        // user Authentication Channel completed
        doAuthenticationChannelCallback(authenticationChannelReq);
        // user Token Request
        OAuthClient.AccessTokenResponse tokenRes = oauth.doBackchannelAuthenticationTokenRequest(TEST_CLIENT_PASSWORD, response.getAuthReqId());
        assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
        IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
        assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
        AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
        // duplicate user Token Request
        tokenRes = oauth.doBackchannelAuthenticationTokenRequest(TEST_CLIENT_PASSWORD, response.getAuthReqId());
        assertThat(tokenRes.getStatusCode(), is(equalTo(400)));
        assertThat(tokenRes.getError(), is(OAuthErrorException.INVALID_GRANT));
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Aggregations

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13