use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class AdminSignatureAlgorithmTest method changeRealmTokenAlgorithm.
@Test
public void changeRealmTokenAlgorithm() throws Exception {
String defaultSignatureAlgorithm = adminClient.realm("master").toRepresentation().getDefaultSignatureAlgorithm();
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"));
} finally {
TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, defaultSignatureAlgorithm);
}
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class FAPI1Test method testFAPIAdvancedLoginWithMTLS.
@Test
public void testFAPIAdvancedLoginWithMTLS() throws Exception {
// Set "advanced" policy
setupPolicyFAPIAdvancedForAllClient();
// Register client with X509
String clientUUID = createClientByAdmin("foo", (ClientRepresentation clientRep) -> {
clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID);
clientRep.setImplicitFlowEnabled(true);
OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep);
clientConfig.setRequestUris(Collections.singletonList(TestApplicationResourceUrls.clientRequestUri()));
clientConfig.setTlsClientAuthSubjectDn("EMAILADDRESS=contact@keycloak.org, CN=Keycloak Intermediate CA, OU=Keycloak, O=Red Hat, ST=MA, C=US");
});
ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(clientUUID);
ClientRepresentation client = clientResource.toRepresentation();
assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType());
// Check nonce and redirectUri
oauth.clientId("foo");
checkNonceAndStateForCurrentClientDuringLogin();
checkRedirectUriForCurrentClientDuringLogin();
// Check login request object required
oauth.openLoginForm();
assertRedirectedToClientWithError(OAuthErrorException.INVALID_REQUEST, false, "Missing parameter: 'request' or 'request_uri'");
// Set request object and correct responseType
TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject requestObject = createValidRequestObjectForSecureRequestObjectExecutor("foo");
// Nonce from method "checkNonceAndStateForCurrentClientDuringLogin()"
requestObject.setNonce("123456");
oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
requestObject.setResponseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
registerRequestObject(requestObject, "foo", org.keycloak.jose.jws.Algorithm.PS256, true);
oauth.openLoginForm();
loginPage.assertCurrent();
String code = loginUserAndGetCode("foo", true);
// Check token not present in the AuthorizationResponse. Check ID Token present, but used as detached signature
Assert.assertNull(getParameterFromUrl(OAuth2Constants.ACCESS_TOKEN, true));
String idTokenParam = getParameterFromUrl(OAuth2Constants.ID_TOKEN, true);
assertIDTokenAsDetachedSignature(idTokenParam, code);
// Check HoK required
OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, null);
assertSuccessfulTokenResponse(tokenResponse);
AccessToken accessToken = oauth.verifyToken(tokenResponse.getAccessToken());
Assert.assertNotNull(accessToken.getCertConf().getCertThumbprint());
// Logout and remove consent of the user for next logins
logoutUserAndRevokeConsent("foo");
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class ClientAuthSignedJWTTest method testDirectGrantRequestSuccess.
private void testDirectGrantRequestSuccess(String algorithm) throws Exception {
ClientRepresentation clientRepresentation = app2;
ClientResource clientResource = getClient(testRealm.getRealm(), clientRepresentation.getId());
clientRepresentation = clientResource.toRepresentation();
try {
// setup Jwks
KeyPair keyPair = setupJwksUrl(algorithm, clientRepresentation, clientResource);
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// test
oauth.clientId("client2");
OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest("test-user@localhost", "password", createSignedRequestToken("client2", getRealmInfoUrl(), privateKey, publicKey, algorithm));
assertEquals(200, response.getStatusCode());
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
events.expectLogin().client("client2").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, "test-user@localhost").detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).assertEvent();
} finally {
// Revert jwks_url settings
revertJwksUriSettings(clientRepresentation, clientResource);
}
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class ClientAuthSignedJWTTest method testAssertionReuse.
@Test
public void testAssertionReuse() throws Exception {
String clientJwt = getClient1SignedJWT();
OAuthClient.AccessTokenResponse response = doClientCredentialsGrantRequest(clientJwt);
assertEquals(200, response.getStatusCode());
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
Assert.assertNotNull(accessToken);
Assert.assertNull(response.getError());
// 2nd attempt to reuse same JWT should fail
response = doClientCredentialsGrantRequest(clientJwt);
assertEquals(400, response.getStatusCode());
assertEquals(OAuthErrorException.INVALID_CLIENT, response.getError());
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class ClientTokenExchangeTest method testImpersonation.
@Test
@UncaughtServerErrorExpected
public void testImpersonation() throws Exception {
testingClient.server().run(ClientTokenExchangeTest::setupRealm);
oauth.realm(TEST);
oauth.clientId("client-exchanger");
Client httpClient = AdminClientUtil.createResteasyClient();
WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT).path("/realms").path(TEST).path("protocol/openid-connect/token");
System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("secret", "user", "password");
String accessToken = tokenResponse.getAccessToken();
TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
AccessToken token = accessTokenVerifier.parse().getToken();
Assert.assertEquals(token.getPreferredUsername(), "user");
Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));
// client-exchanger can impersonate from token "user" to user "impersonated-user"
{
Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("client-exchanger", "secret")).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.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user")));
org.junit.Assert.assertEquals(200, response.getStatus());
AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
response.close();
String exchangedTokenString = accessTokenResponse.getToken();
TokenVerifier<AccessToken> verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class);
AccessToken exchangedToken = verifier.parse().getToken();
Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor());
Assert.assertNull(exchangedToken.getAudience());
Assert.assertEquals("impersonated-user", exchangedToken.getPreferredUsername());
Assert.assertNull(exchangedToken.getRealmAccess());
Object impersonatorRaw = exchangedToken.getOtherClaims().get("impersonator");
Assert.assertThat(impersonatorRaw, instanceOf(Map.class));
Map impersonatorClaim = (Map) impersonatorRaw;
Assert.assertEquals(token.getSubject(), impersonatorClaim.get("id"));
Assert.assertEquals("user", impersonatorClaim.get("username"));
}
// client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client
{
Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("client-exchanger", "secret")).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.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user").param(OAuth2Constants.AUDIENCE, "target")));
org.junit.Assert.assertEquals(200, response.getStatus());
AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
response.close();
String exchangedTokenString = accessTokenResponse.getToken();
TokenVerifier<AccessToken> verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class);
AccessToken exchangedToken = verifier.parse().getToken();
Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor());
Assert.assertEquals("target", exchangedToken.getAudience()[0]);
Assert.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user");
Assert.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example"));
}
}
Aggregations