use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class OIDCProtocolMappersTest method testGroupAttributeTwoGroupMultiValueAggregate.
@Test
public void testGroupAttributeTwoGroupMultiValueAggregate() throws Exception {
// get the user
UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
// create two groups with two values (one is the same value)
GroupRepresentation group1 = new GroupRepresentation();
group1.setName("group1");
group1.setAttributes(new HashMap<>());
group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
adminClient.realm("test").groups().add(group1);
group1 = adminClient.realm("test").getGroupByPath("/group1");
userResource.joinGroup(group1.getId());
GroupRepresentation group2 = new GroupRepresentation();
group2.setName("group2");
group2.setAttributes(new HashMap<>());
group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));
adminClient.realm("test").groups().add(group2);
group2 = adminClient.realm("test").getGroupByPath("/group2");
userResource.joinGroup(group2.getId());
// create the attribute mapper
ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close();
try {
// test it
OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");
IDToken idToken = oauth.verifyIDToken(response.getIdToken());
assertNotNull(idToken.getOtherClaims());
assertNotNull(idToken.getOtherClaims().get("group-value"));
assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
assertEquals(3, ((List) idToken.getOtherClaims().get("group-value")).size());
assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1"));
assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2"));
assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value3"));
} finally {
// revert
userResource.leaveGroup(group1.getId());
adminClient.realm("test").groups().group(group1.getId()).remove();
userResource.leaveGroup(group2.getId());
adminClient.realm("test").groups().group(group2.getId()).remove();
deleteMappers(protocolMappers);
}
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class ParTest method testSuccessfulUsingRequestParameter.
@Test
public void testSuccessfulUsingRequestParameter() throws Exception {
try {
// setup PAR realm settings
int requestUriLifespan = 45;
setParRealmSettings(requestUriLifespan);
// create client dynamically
String clientId = createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
clientRep.setRequirePushedAuthorizationRequests(Boolean.TRUE);
clientRep.setRedirectUris(new ArrayList<>(Arrays.asList(CLIENT_REDIRECT_URI)));
});
oauth.clientId(clientId);
OIDCClientRepresentation oidcCRep = getClientDynamically(clientId);
String clientSecret = oidcCRep.getClientSecret();
assertEquals(Boolean.TRUE, oidcCRep.getRequirePushedAuthorizationRequests());
assertTrue(oidcCRep.getRedirectUris().contains(CLIENT_REDIRECT_URI));
assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, oidcCRep.getTokenEndpointAuthMethod());
TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject requestObject = new TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject();
requestObject.id(KeycloakModelUtils.generateId());
requestObject.iat(Long.valueOf(Time.currentTime()));
requestObject.exp(requestObject.getIat() + Long.valueOf(300));
requestObject.nbf(requestObject.getIat());
requestObject.setClientId(oauth.getClientId());
requestObject.setResponseType("code");
requestObject.setRedirectUriParam(CLIENT_REDIRECT_URI);
requestObject.setScope("openid");
requestObject.setNonce(KeycloakModelUtils.generateId());
byte[] contentBytes = JsonSerialization.writeValueAsBytes(requestObject);
String encodedRequestObject = Base64Url.encode(contentBytes);
TestOIDCEndpointsApplicationResource client = testingClient.testApp().oidcClientEndpoints();
// use and set jwks_url
ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm(oauth.getRealm()), oauth.getClientId());
ClientRepresentation clientRep = clientResource.toRepresentation();
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(TestApplicationResourceUrls.clientJwksUri());
clientResource.update(clientRep);
client.generateKeys(org.keycloak.crypto.Algorithm.RS256);
client.registerOIDCRequest(encodedRequestObject, org.keycloak.crypto.Algorithm.RS256);
// do not send any other parameter but the request request parameter
oauth.request(client.getOIDCRequest());
oauth.responseType(null);
oauth.redirectUri(null);
oauth.scope(null);
ParResponse pResp = oauth.doPushedAuthorizationRequest(clientId, clientSecret);
assertEquals(201, pResp.getStatusCode());
String requestUri = pResp.getRequestUri();
assertEquals(requestUriLifespan, pResp.getExpiresIn());
// Authorization Request with request_uri of PAR
// remove parameters as query strings of uri
oauth.redirectUri(null);
oauth.scope(null);
oauth.responseType(null);
oauth.request(null);
oauth.requestUri(requestUri);
OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
// Token Request
// get tokens, it needed. https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
oauth.redirectUri(CLIENT_REDIRECT_URI);
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(loginResponse.getCode(), clientSecret);
assertEquals(200, res.getStatusCode());
oauth.verifyToken(res.getAccessToken());
IDToken idToken = oauth.verifyIDToken(res.getIdToken());
assertEquals(requestObject.getNonce(), idToken.getNonce());
} finally {
restoreParRealmSettings();
}
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class OIDCBasicResponseTypeCodeTest method testAuthzResponseAndRetrieveIDTokens.
@Override
protected List<IDToken> testAuthzResponseAndRetrieveIDTokens(OAuthClient.AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) {
Assert.assertEquals(OIDCResponseType.CODE, loginEvent.getDetails().get(Details.RESPONSE_TYPE));
Assert.assertNull(authzResponse.getAccessToken());
Assert.assertNull(authzResponse.getIdToken());
OAuthClient.AccessTokenResponse authzResponse2 = sendTokenRequestAndGetResponse(loginEvent);
IDToken idToken2 = oauth.verifyIDToken(authzResponse2.getIdToken());
// Validate "at_hash"
assertValidAccessTokenHash(idToken2.getAccessTokenHash(), authzResponse2.getAccessToken());
// Validate if token_type is null
Assert.assertNull(authzResponse.getTokenType());
// Validate if expires_in is null
Assert.assertNull(authzResponse.getExpiresIn());
return Collections.singletonList(idToken2);
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class AbstractOIDCScopeTest method sendTokenRequest.
protected AbstractOIDCScopeTest.Tokens sendTokenRequest(EventRepresentation loginEvent, String userId, String expectedScope, String clientId) {
String sessionId = loginEvent.getSessionId();
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
Assert.assertEquals(200, response.getStatusCode());
// Test scopes
log.info("expectedScopes = " + expectedScope);
log.info("responseScopes = " + response.getScope());
assertScopes(expectedScope, response.getScope());
IDToken idToken = oauth.verifyIDToken(response.getIdToken());
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
// Test scope in the access token
assertScopes(expectedScope, accessToken.getScope());
EventRepresentation codeToTokenEvent = events.expectCodeToToken(codeId, sessionId).user(userId).client(clientId).assertEvent();
// Test scope in the event
assertScopes(expectedScope, codeToTokenEvent.getDetails().get(Details.SCOPE));
return new AbstractOIDCScopeTest.Tokens(idToken, accessToken, response.getRefreshToken());
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class IdTokenEncryptionTest method testIdTokenSignatureAndEncryption.
private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAlgorithm, String encAlgorithm) {
ClientResource clientResource = null;
ClientRepresentation clientRep = null;
try {
// generate and register encryption key onto client
TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
oidcClientEndpointsResource.generateKeys(algAlgorithm);
clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
clientRep = clientResource.toRepresentation();
// set id token signature algorithm and encryption algorithms
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(sigAlgorithm);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(algAlgorithm);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(encAlgorithm);
// use and set jwks_url
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
String jwksUrl = TestApplicationResourceUrls.clientJwksUri();
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(jwksUrl);
clientResource.update(clientRep);
// get id token
OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
String code = response.getCode();
OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
// parse JWE and JOSE Header
String jweStr = tokenResponse.getIdToken();
String[] parts = jweStr.split("\\.");
Assert.assertEquals(parts.length, 5);
// get decryption key
// not publickey , use privateKey
Map<String, String> keyPair = oidcClientEndpointsResource.getKeysAsPem();
PrivateKey decryptionKEK = PemUtils.decodePrivateKey(keyPair.get("privateKey"));
// a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field
JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]);
Assert.assertEquals("JWT", jweHeader.getContentType());
// verify and decrypt JWE
JWEAlgorithmProvider algorithmProvider = getJweAlgorithmProvider(algAlgorithm);
JWEEncryptionProvider encryptionProvider = getJweEncryptionProvider(encAlgorithm);
byte[] decodedString = TokenUtil.jweKeyEncryptionVerifyAndDecode(decryptionKEK, jweStr, algorithmProvider, encryptionProvider);
String idTokenString = new String(decodedString, "UTF-8");
// verify JWS
IDToken idToken = oauth.verifyIDToken(idTokenString);
Assert.assertEquals("test-user@localhost", idToken.getPreferredUsername());
Assert.assertEquals("test-app", idToken.getIssuedFor());
} catch (JWEException | UnsupportedEncodingException e) {
Assert.fail();
} finally {
clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
clientRep = clientResource.toRepresentation();
// revert id token signature algorithm and encryption algorithms
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(Algorithm.RS256);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(null);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(null);
// revert jwks_url settings
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(false);
OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(null);
clientResource.update(clientRep);
}
}
Aggregations