Search in sources :

Example 46 with AccessTokenResponse

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

the class TwitterIdentityProvider method exchangeStoredToken.

protected Response exchangeStoredToken(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(authorizedClient.getRealm(), tokenSubject, getConfig().getAlias());
    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();
}
Also used : FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 47 with AccessTokenResponse

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

the class TwitterIdentityProvider method exchangeSessionToken.

protected Response exchangeSessionToken(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    String accessToken = tokenUserSession.getNote(IdentityProvider.FEDERATED_ACCESS_TOKEN);
    if (accessToken == null) {
        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();
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 48 with AccessTokenResponse

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

the class EntitlementAPITest method testPermissionsAcrossResourceServers.

@Test
public void testPermissionsAcrossResourceServers() throws Exception {
    String rsAId;
    try (Response response = getRealm().clients().create(ClientBuilder.create().clientId("rs-a").secret("secret").serviceAccount().authorizationServicesEnabled(true).build())) {
        rsAId = ApiUtil.getCreatedId(response);
    }
    String rsBId;
    try (Response response = getRealm().clients().create(ClientBuilder.create().clientId("rs-b").secret("secret").serviceAccount().authorizationServicesEnabled(true).build())) {
        rsBId = ApiUtil.getCreatedId(response);
    }
    ClientResource rsB = getRealm().clients().get(rsBId);
    rsB.authorization().resources().create(new ResourceRepresentation("Resource A"));
    JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation();
    grantPolicy.setName("Grant Policy");
    grantPolicy.setCode("$evaluation.grant();");
    rsB.authorization().policies().js().create(grantPolicy);
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName("Resource A Permission");
    permission.addResource("Resource A");
    permission.addPolicy(grantPolicy.getName());
    rsB.authorization().permissions().resource().create(permission);
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    Configuration config = authzClient.getConfiguration();
    config.setResource("rs-a");
    authzClient = AuthzClient.create(config);
    AccessTokenResponse accessTokenResponse = authzClient.obtainAccessToken();
    AccessToken accessToken = toAccessToken(accessTokenResponse.getToken());
    config.setResource("rs-b");
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission("Resource A");
    AuthorizationResponse response = authzClient.authorization(accessTokenResponse.getToken()).authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    assertEquals("Resource A", permissions.iterator().next().getResourceName());
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Configuration(org.keycloak.authorization.client.Configuration) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) ClientResource(org.keycloak.admin.client.resource.ClientResource) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test)

Example 49 with AccessTokenResponse

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

the class ConfigCredentialsCmd method process.

public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    // check server
    if (server == null) {
        throw new IllegalArgumentException("Required option not specified: --server");
    }
    try {
        new URL(server);
    } catch (Exception e) {
        throw new RuntimeException("Invalid server endpoint url: " + server, e);
    }
    if (realm == null)
        throw new IllegalArgumentException("Required option not specified: --realm");
    String signedRequestToken = null;
    boolean clientSet = clientId != null;
    applyDefaultOptionValues();
    String grantTypeForAuthentication = null;
    if (user != null) {
        grantTypeForAuthentication = OAuth2Constants.PASSWORD;
        printErr("Logging into " + server + " as user " + user + " of realm " + realm);
        // if user was set there needs to be a password so we can authenticate
        if (password == null) {
            password = readSecret("Enter password: ", commandInvocation);
        }
        // if secret was set to be read from stdin, then ask for it
        if ("-".equals(secret) && keystore == null) {
            secret = readSecret("Enter client secret: ", commandInvocation);
        }
    } else if (keystore != null || secret != null || clientSet) {
        grantTypeForAuthentication = OAuth2Constants.CLIENT_CREDENTIALS;
        printErr("Logging into " + server + " as " + "service-account-" + clientId + " of realm " + realm);
        if (keystore == null) {
            if (secret == null) {
                secret = readSecret("Enter client secret: ", commandInvocation);
            }
        }
    }
    if (keystore != null) {
        if (secret != null) {
            throw new IllegalArgumentException("Can't use both --keystore and --secret");
        }
        if (!new File(keystore).isFile()) {
            throw new RuntimeException("No such keystore file: " + keystore);
        }
        if (storePass == null) {
            storePass = readSecret("Enter keystore password: ", commandInvocation);
            keyPass = readSecret("Enter key password: ", commandInvocation);
        }
        if (keyPass == null) {
            keyPass = storePass;
        }
        if (alias == null) {
            alias = clientId;
        }
        String realmInfoUrl = server + "/realms/" + realm;
        signedRequestToken = AuthUtil.getSignedRequestToken(keystore, storePass, keyPass, alias, sigLifetime, clientId, realmInfoUrl);
    }
    // if only server and realm are set, just save config and be done
    if (user == null && secret == null && keystore == null) {
        getHandler().saveMergeConfig(config -> {
            config.setServerUrl(server);
            config.setRealm(realm);
        });
        return CommandResult.SUCCESS;
    }
    setupTruststore(copyWithServerInfo(loadConfig()), commandInvocation);
    // now use the token endpoint to retrieve access token, and refresh token
    AccessTokenResponse tokens = signedRequestToken != null ? getAuthTokensByJWT(server, realm, user, password, clientId, signedRequestToken) : secret != null ? getAuthTokensBySecret(server, realm, user, password, clientId, secret) : getAuthTokens(server, realm, user, password, clientId);
    Long sigExpiresAt = signedRequestToken == null ? null : System.currentTimeMillis() + sigLifetime * 1000;
    // save tokens to config file
    saveTokens(tokens, server, realm, clientId, signedRequestToken, sigExpiresAt, secret, grantTypeForAuthentication);
    return CommandResult.SUCCESS;
}
Also used : File(java.io.File) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) URL(java.net.URL) CommandException(org.jboss.aesh.console.command.CommandException)

Example 50 with AccessTokenResponse

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

the class DefaultTokenExchangeProvider method exchangeClientToSAML2Client.

protected Response exchangeClientToSAML2Client(UserModel targetUser, UserSessionModel targetUserSession, String requestedTokenType, ClientModel targetClient, String audience, String scope) {
    // Create authSession with target SAML 2.0 client and authenticated user
    LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
    SamlService samlService = (SamlService) factory.createProtocolEndpoint(realm, event);
    ResteasyProviderFactory.getInstance().injectProperties(samlService);
    AuthenticationSessionModel authSession = samlService.getOrCreateLoginSessionForIdpInitiatedSso(session, realm, targetClient, null);
    if (authSession == null) {
        logger.error("SAML assertion consumer url not set up");
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires assertion consumer url set up", Response.Status.BAD_REQUEST);
    }
    authSession.setAuthenticatedUser(targetUser);
    event.session(targetUserSession);
    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(this.session, targetUserSession, authSession);
    updateUserSessionFromClientAuth(targetUserSession);
    // Create SAML 2.0 Assertion Response
    SamlClient samlClient = new SamlClient(targetClient);
    SamlProtocol samlProtocol = new TokenExchangeSamlProtocol(samlClient).setEventBuilder(event).setHttpHeaders(headers).setRealm(realm).setSession(session).setUriInfo(session.getContext().getUri());
    Response samlAssertion = samlProtocol.authenticated(authSession, targetUserSession, clientSessionCtx);
    if (samlAssertion.getStatus() != 200) {
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Can not get SAML 2.0 token", Response.Status.BAD_REQUEST);
    }
    String xmlString = (String) samlAssertion.getEntity();
    String encodedXML = Base64Url.encode(xmlString.getBytes(GeneralConstants.SAML_CHARSET));
    int assertionLifespan = samlClient.getAssertionLifespan();
    AccessTokenResponse res = new AccessTokenResponse();
    res.setToken(encodedXML);
    res.setTokenType("Bearer");
    res.setExpiresIn(assertionLifespan <= 0 ? realm.getAccessCodeLifespan() : assertionLifespan);
    res.setOtherClaims(OAuth2Constants.ISSUED_TOKEN_TYPE, requestedTokenType);
    event.detail(Details.AUDIENCE, targetClient.getClientId());
    event.success();
    return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) TokenExchangeSamlProtocol(org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) TokenExchangeSamlProtocol(org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol) SamlClient(org.keycloak.protocol.saml.SamlClient) SamlService(org.keycloak.protocol.saml.SamlService) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) LoginProtocolFactory(org.keycloak.protocol.LoginProtocolFactory) ClientSessionContext(org.keycloak.models.ClientSessionContext) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) LoginProtocol(org.keycloak.protocol.LoginProtocol) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Aggregations

AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)73 Response (javax.ws.rs.core.Response)30 Test (org.junit.Test)29 OAuthClient (org.keycloak.testsuite.util.OAuthClient)25 Client (javax.ws.rs.client.Client)24 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)17 Form (javax.ws.rs.core.Form)15 WebTarget (javax.ws.rs.client.WebTarget)14 AccessToken (org.keycloak.representations.AccessToken)14 IOException (java.io.IOException)12 ClientResource (org.keycloak.admin.client.resource.ClientResource)7 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)7 AuthzClient (org.keycloak.authorization.client.AuthzClient)5 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)5 CorsErrorResponseException (org.keycloak.services.CorsErrorResponseException)5 UncaughtServerErrorExpected (org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)5 InputStream (java.io.InputStream)4 URI (java.net.URI)4 NameValuePair (org.apache.http.NameValuePair)4 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)4