org.keycloak.representations.AccessTokenResponse Java Examples

The following examples show how to use org.keycloak.representations.AccessTokenResponse. 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: ConfigUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void saveTokens(AccessTokenResponse tokens, String endpoint, String realm, String clientId, String signKey, Long sigExpiresAt, String secret) {
    handler.saveMergeConfig(config -> {
        config.setServerUrl(endpoint);
        config.setRealm(realm);

        RealmConfigData realmConfig = config.ensureRealmConfigData(endpoint, realm);
        realmConfig.setToken(tokens.getToken());
        realmConfig.setRefreshToken(tokens.getRefreshToken());
        realmConfig.setSigningToken(signKey);
        realmConfig.setSecret(secret);
        realmConfig.setExpiresAt(System.currentTimeMillis() + tokens.getExpiresIn() * 1000);
        realmConfig.setRefreshExpiresAt(tokens.getRefreshExpiresIn() == 0 ?
                Long.MAX_VALUE : System.currentTimeMillis() + tokens.getRefreshExpiresIn() * 1000);
        realmConfig.setSigExpiresAt(sigExpiresAt);
        realmConfig.setClientId(clientId);
    });
}
 
Example #2
Source File: UmaGrantTypeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testObtainRptUsingAccessToken() throws Exception {
    AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password");
    AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB"));
    String rpt = response.getToken();

    assertNotNull(rpt);
    assertFalse(response.isUpgraded());

    AccessToken accessToken = toAccessToken(rpt);
    AccessToken.Authorization authorization = accessToken.getAuthorization();

    assertNotNull(authorization);

    Collection<Permission> permissions = authorization.getPermissions();

    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
}
 
Example #3
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestWithoutClaimsFromPublicClient() {
    oauth.realm("authz-test");
    oauth.clientId(PUBLIC_TEST_CLIENT);

    oauth.doLogin("marta", "password");

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

    AuthorizationRequest request = new AuthorizationRequest();

    request.addPermission("Resource 13");

    assertResponse(new Metadata(), () -> getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(response.getAccessToken()).authorize(request));
}
 
Example #4
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidRequestWithClaimsFromPublicClient() throws IOException {
    oauth.realm("authz-test");
    oauth.clientId(PUBLIC_TEST_CLIENT);

    oauth.doLogin("marta", "password");

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

    AuthorizationRequest request = new AuthorizationRequest();

    request.addPermission("Resource 13");
    HashMap<Object, Object> obj = new HashMap<>();

    obj.put("claim-a", "claim-a");

    request.setClaimToken(Base64Url.encode(JsonSerialization.writeValueAsBytes(obj)));
    this.expectedException.expect(AuthorizationDeniedException.class);
    this.expectedException.expectCause(Matchers.allOf(Matchers.instanceOf(HttpResponseException.class), Matchers.hasProperty("statusCode", Matchers.is(403))));
    this.expectedException.expectMessage("Public clients are not allowed to send claims");
    this.expectedException.reportMissingExceptionWithMessage("Should fail, public clients not allowed");

    getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(response.getAccessToken()).authorize(request);
}
 
Example #5
Source File: AdminSignatureAlgorithmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void changeRealmTokenAlgorithm() throws Exception {
    TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256);

    try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString())) {
        AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class);
        assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name());

        assertNotNull(adminClient.realms().findAll());

        String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami";

        JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson();
        assertNotNull(jsonNode.get("realm"));
        assertNotNull(jsonNode.get("userId"));
    }
}
 
Example #6
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 #7
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void testBadImpersonator() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);

    oauth.realm(TEST);
    oauth.clientId("client-exchanger");

    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "bad-impersonator", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "bad-impersonator");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));

    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);

    // test that user does not have impersonator permission
    {
        params.put(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user");
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "client-exchanger", "secret", params);
        Assert.assertEquals(403, response.getStatusCode());
    }
}
 
Example #8
Source File: TwitterIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response exchangeStoredToken(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(tokenSubject, getConfig().getAlias(), authorizedClient.getRealm());
    if (model == null || model.getToken() == null) {
        return exchangeNotLinked(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    String accessToken = model.getToken();
    if (accessToken == null) {
        model.setToken(null);
        session.users().updateFederatedIdentity(authorizedClient.getRealm(), tokenSubject, model);
        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, TWITTER_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example #9
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response exchangeSessionToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
    if (accessToken == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        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 #10
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_postMethod_header_textEntity() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
        Response response = userInfoTarget.request()
                .header(HttpHeaders.AUTHORIZATION, "bearer " + accessTokenResponse.getToken())
                .post(Entity.text(""));

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example #11
Source File: KeycloakAdminClient.java    From nexus3-keycloak-plugin with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponse obtainAccessToken(String username, String password) {
    URI uri = KeycloakUriBuilder.fromUri(this.config.getAuthServerUrl())
                                .path(ServiceUrlConstants.TOKEN_PATH)
                                .build(this.config.getRealm());
    HttpMethod<AccessTokenResponse> httpMethod = getHttp().post(uri);

    httpMethod = httpMethod.form()
                           .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
                           .param("username", username)
                           .param("password", password);

    if (this.config.isPublicClient()) {
        httpMethod.param(OAuth2Constants.CLIENT_ID, this.config.getResource());
    } else {
        httpMethod.authorizationBasic(this.config.getResource(),
                                      this.config.getCredentials().get("secret").toString());
    }

    return httpMethod.response().json(AccessTokenResponse.class).execute();
}
 
Example #12
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_postMethod_header() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
        Response response = userInfoTarget.request()
                .header(HttpHeaders.AUTHORIZATION, "bearer " + accessTokenResponse.getToken())
                .post(Entity.form(new Form()));

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example #13
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_postMethod_body() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        Form form = new Form();
        form.param("access_token", accessTokenResponse.getToken());

        WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
        Response response = userInfoTarget.request()
                .post(Entity.form(form));

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example #14
Source File: KeycloakAuthentication.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponse login(
        String realm,
        String clientId,
        String clientSecret,
        String username,
        String password
) throws AuthenticationException {
    return login(
            keycloakConfigProperties.getUrl(),
            realm,
            clientId,
            clientSecret,
            username,
            password
    );
}
 
Example #15
Source File: ProductServiceAccountServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setTokens(HttpServletRequest req, KeycloakDeployment deployment, AccessTokenResponse tokenResponse) throws IOException, VerificationException {
    String token = tokenResponse.getToken();
    String refreshToken = tokenResponse.getRefreshToken();
    AdapterTokenVerifier.VerifiedTokens parsedTokens = AdapterTokenVerifier.verifyTokens(token, tokenResponse.getIdToken(), deployment);
    AccessToken tokenParsed = parsedTokens.getAccessToken();
    req.getSession().setAttribute(TOKEN, token);
    req.getSession().setAttribute(REFRESH_TOKEN, refreshToken);
    req.getSession().setAttribute(TOKEN_PARSED, tokenParsed);
}
 
Example #16
Source File: KeycloakDirectAccessGrantService.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
@Override
public RefreshableKeycloakSecurityContext login(String username, String password) throws VerificationException {

    final MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    final HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    body.set("username", username);
    body.set("password", password);
    body.set(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);

    AccessTokenResponse response = template.postForObject(keycloakDeployment.getTokenUrl(), new HttpEntity<>(body, headers), AccessTokenResponse.class);

    return KeycloakSpringAdapterUtils.createKeycloakSecurityContext(keycloakDeployment, response);
}
 
Example #17
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponse grantToken() {
    Form form = new Form().param(GRANT_TYPE, accessTokenGrantType);
    if (PASSWORD.equals(accessTokenGrantType)) {
        form.param("username", config.getUsername())
            .param("password", config.getPassword());
    }

    if (config.isPublicClient()) {
        form.param(CLIENT_ID, config.getClientId());
    }

    int requestTime = Time.currentTime();
    synchronized (this) {
        currentToken = tokenService.grantToken(config.getRealm(), form.asMap());
        expirationTime = requestTime + currentToken.getExpiresIn();
    }
    return currentToken;
}
 
Example #18
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public synchronized AccessTokenResponse refreshToken() {
    Form form = new Form().param(GRANT_TYPE, REFRESH_TOKEN)
                          .param(REFRESH_TOKEN, currentToken.getRefreshToken());

    if (config.isPublicClient()) {
        form.param(CLIENT_ID, config.getClientId());
    }

    try {
        int requestTime = Time.currentTime();

        currentToken = tokenService.refreshToken(config.getRealm(), form.asMap());
        expirationTime = requestTime + currentToken.getExpiresIn();
        return currentToken;
    } catch (BadRequestException e) {
        return grantToken();
    }
}
 
Example #19
Source File: ConfigUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void saveTokens(AccessTokenResponse tokens, String endpoint, String realm, String clientId, String signKey, Long sigExpiresAt, String secret) {
    handler.saveMergeConfig(config -> {
        config.setServerUrl(endpoint);
        config.setRealm(realm);

        RealmConfigData realmConfig = config.ensureRealmConfigData(endpoint, realm);
        realmConfig.setToken(tokens.getToken());
        realmConfig.setRefreshToken(tokens.getRefreshToken());
        realmConfig.setSigningToken(signKey);
        realmConfig.setSecret(secret);
        realmConfig.setExpiresAt(System.currentTimeMillis() + tokens.getExpiresIn() * 1000);
        realmConfig.setRefreshExpiresAt(tokens.getRefreshExpiresIn() == 0 ?
                Long.MAX_VALUE : System.currentTimeMillis() + tokens.getRefreshExpiresIn() * 1000);
        realmConfig.setSigExpiresAt(sigExpiresAt);
        realmConfig.setClientId(clientId);
    });
}
 
Example #20
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 #21
Source File: AuthzClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains an access token using the client credentials.
 *
 * @return an {@link AccessTokenResponse}
 */
public AccessTokenResponse obtainAccessToken() {
    return this.http.<AccessTokenResponse>post(this.serverConfiguration.getTokenEndpoint())
            .authentication()
                .client()
            .response()
                .json(AccessTokenResponse.class)
            .execute();
}
 
Example #22
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_getMethod_header() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);
        Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example #23
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticationFinished(AuthenticationSessionModel authSession, BrokeredIdentityContext context) {
    AccessTokenResponse tokenResponse = (AccessTokenResponse) context.getContextData().get(FEDERATED_ACCESS_TOKEN_RESPONSE);
    int currentTime = Time.currentTime();
    long expiration = tokenResponse.getExpiresIn() > 0 ? tokenResponse.getExpiresIn() + currentTime : 0;
    authSession.setUserSessionNote(FEDERATED_TOKEN_EXPIRATION, Long.toString(expiration));
    authSession.setUserSessionNote(FEDERATED_REFRESH_TOKEN, tokenResponse.getRefreshToken());
    authSession.setUserSessionNote(FEDERATED_ACCESS_TOKEN, tokenResponse.getToken());
    authSession.setUserSessionNote(FEDERATED_ID_TOKEN, tokenResponse.getIdToken());
}
 
Example #24
Source File: ClientInitiatedAccountLinkTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getToken(OAuthClient.AccessTokenResponse response, Client httpClient) throws Exception {
    String idpToken =  httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
            .path("realms")
            .path("child/broker")
            .path(PARENT_IDP)
            .path("token")
            .request()
            .header("Authorization", "Bearer " + response.getAccessToken())
            .get(String.class);
    AccessTokenResponse res = JsonSerialization.readValue(idpToken, AccessTokenResponse.class);
    return res.getToken();
}
 
Example #25
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String readToken(String client) throws Exception {
    String json = getTokenResponse(client);
    if (json == null) return null;


    if (json != null) {
        try {
            AccessTokenResponse tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
            if (Time.currentTime() < tokenResponse.getExpiresIn()) {
                return tokenResponse.getToken();
            }
            AdapterConfig config = getConfig();
            KeycloakInstalled installed = new KeycloakInstalled(KeycloakDeploymentBuilder.build(config));
            installed.refreshToken(tokenResponse.getRefreshToken());
            processResponse(installed, client);
            return tokenResponse.getToken();
        } catch (Exception e) {
            File tokenFile = getTokenFilePath(client);
            if (tokenFile.exists()) {
                tokenFile.delete();
            }

            return null;
        }
    }
    return null;

}
 
Example #26
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Response refreshTokenGrant() {
    String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
    if (refreshToken == null) {
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
    }

    AccessTokenResponse res;
    try {
        // KEYCLOAK-6771 Certificate Bound Token
        TokenManager.RefreshResult result = tokenManager.refreshAccessToken(session, session.getContext().getUri(), clientConnection, realm, client, refreshToken, event, headers, request);
        res = result.getResponse();

        if (!result.isOfflineToken()) {
            UserSessionModel userSession = session.sessions().getUserSession(realm, res.getSessionState());
            AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
            updateClientSession(clientSession);
            updateUserSessionFromClientAuth(userSession);
        }

    } catch (OAuthErrorException e) {
        logger.trace(e.getMessage(), e);
        // KEYCLOAK-6771 Certificate Bound Token
        if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) {
            event.error(Errors.NOT_ALLOWED);
            throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED);
        } else {
            event.error(Errors.INVALID_TOKEN);
            throw new CorsErrorResponseException(cors, e.getError(), e.getDescription(), Response.Status.BAD_REQUEST);
        }
    }

    event.success();

    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
 
Example #27
Source File: AdminClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void logout(HttpServletRequest request, AccessTokenResponse res) throws IOException {

        HttpClient client = new DefaultHttpClient();


        try {
            HttpPost post = new HttpPost(KeycloakUriBuilder.fromUri(UriUtils.getOrigin(request.getRequestURL().toString()) + "/auth")
                    .path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH)
                    .build("demo"));
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, res.getRefreshToken()));
            formparams.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, "admin-client"));
            UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(form);
            HttpResponse response = client.execute(post);
            boolean status = response.getStatusLine().getStatusCode() != 204;
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            InputStream is = entity.getContent();
            if (is != null) is.close();
            if (status) {
                throw new RuntimeException("failed to logout");
            }
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
 
Example #28
Source File: UmaGrantTypeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getIdToken(String username, String password) {
    oauth.realm("authz-test");
    oauth.clientId("test-app");
    oauth.openLoginForm();
    OAuthClient.AuthorizationEndpointResponse resp = oauth.doLogin(username, password);
    String code = resp.getCode();
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, password);
    return response.getIdToken();
}
 
Example #29
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestCallWithAccessTokenAsQueryParameter() {

    Client client = new ResteasyClientBuilder().httpEngine(new FollowRedirectsEngine()).build();
    try {
        WebTarget webTarget = client.target(testRealmPage.toString() + "/protocol/openid-connect/token");

        Form form = new Form();
        form.param("grant_type", "password");
        form.param("client_id", "customer-portal-public");
        form.param("username", "[email protected]");
        form.param("password", "password");
        Response response = webTarget.request().post(Entity.form(form));

        Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();

        String accessToken = tokenResponse.getToken();

        // test without token
        response = client.target(customerDb.getInjectedUrl().toString()).request().get();
        Assert.assertEquals(401, response.getStatus());
        response.close();
        // test with access_token as QueryParamter
        response = client.target(customerDb.getInjectedUrl().toString()).queryParam("access_token", accessToken).request().get();
        Assert.assertEquals(200, response.getStatus());
        response.close();
    } finally {
        client.close();
    }
}
 
Example #30
Source File: TokenCallable.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains an access token using the client credentials.
 *
 * @return an {@link AccessTokenResponse}
 */
AccessTokenResponse obtainAccessToken() {
    return this.http.<AccessTokenResponse>post(this.serverConfiguration.getTokenEndpoint())
            .authentication()
            .client()
            .response()
            .json(AccessTokenResponse.class)
            .execute();
}