use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class ClientAuthSignedJWTTest method assertSuccess.
private void assertSuccess(OAuthClient.AccessTokenResponse response, String clientId, String userId, String userName) {
assertEquals(200, response.getStatusCode());
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
events.expectClientLogin().client(clientId).user(userId).session(accessToken.getSessionState()).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, userName).detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).assertEvent();
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class ClientAuthSignedJWTTest method testClientWithGeneratedKeys.
private void testClientWithGeneratedKeys(String format) throws Exception {
ClientRepresentation client = app3;
UserRepresentation user = defaultUser;
final String keyAlias = "somekey";
final String keyPassword = "pwd1";
final String storePassword = "pwd2";
// Generate new keystore (which is intended for sending to the user and store in a client app)
// with public/private keys; in KC, store the certificate itself
KeyStoreConfig keyStoreConfig = new KeyStoreConfig();
keyStoreConfig.setFormat(format);
keyStoreConfig.setKeyPassword(keyPassword);
keyStoreConfig.setStorePassword(storePassword);
keyStoreConfig.setKeyAlias(keyAlias);
client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR);
// Generate the keystore and save the new certificate in client (in KC)
byte[] keyStoreBytes = getClientAttributeCertificateResource(testRealm.getRealm(), client.getId()).generateAndGetKeystore(keyStoreConfig);
ByteArrayInputStream keyStoreIs = new ByteArrayInputStream(keyStoreBytes);
KeyStore keyStore = getKeystore(keyStoreIs, storePassword, format);
keyStoreIs.close();
client = getClient(testRealm.getRealm(), client.getId()).toRepresentation();
X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(keyAlias);
assertCertificate(client, certOld, KeycloakModelUtils.getPemFromCertificate(x509Cert));
// Try to login with the new keys
oauth.clientId(client.getClientId());
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword.toCharArray());
KeyPair keyPair = new KeyPair(x509Cert.getPublicKey(), privateKey);
OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest(user.getUsername(), user.getCredentials().get(0).getValue(), getClientSignedJWT(keyPair, client.getClientId()));
assertEquals(200, response.getStatusCode());
AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
events.expectLogin().client(client.getClientId()).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, user.getUsername()).detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).assertEvent();
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class AccessTokenDuplicateEmailsTest method loginWithSecondDuplicateEmailUser.
@Test
public void loginWithSecondDuplicateEmailUser() throws Exception {
oauth.doLogin("duplicate-email-user2", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
assertEquals(200, response.getStatusCode());
AccessToken token = oauth.verifyToken(response.getAccessToken());
assertEquals(findUserByUsername(adminClient.realm("test-duplicate-emails"), "duplicate-email-user2").getId(), token.getSubject());
assertEquals("duplicate-email-user@localhost", token.getEmail());
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class PolicyEvaluationResponseBuilder method build.
public static PolicyEvaluationResponse build(PolicyEvaluationService.EvaluationDecisionCollector decision, ResourceServer resourceServer, AuthorizationProvider authorization, KeycloakIdentity identity) {
PolicyEvaluationResponse response = new PolicyEvaluationResponse();
List<PolicyEvaluationResponse.EvaluationResultRepresentation> resultsRep = new ArrayList<>();
AccessToken accessToken = identity.getAccessToken();
AccessToken.Authorization authorizationData = new AccessToken.Authorization();
authorizationData.setPermissions(decision.results());
accessToken.setAuthorization(authorizationData);
ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getId());
if (!accessToken.hasAudience(clientModel.getClientId())) {
accessToken.audience(clientModel.getClientId());
}
response.setRpt(accessToken);
Collection<Result> results = decision.getResults();
if (results.stream().anyMatch(evaluationResult -> evaluationResult.getEffect().equals(Decision.Effect.DENY))) {
response.setStatus(DecisionEffect.DENY);
} else {
response.setStatus(DecisionEffect.PERMIT);
}
for (Result result : results) {
PolicyEvaluationResponse.EvaluationResultRepresentation rep = new PolicyEvaluationResponse.EvaluationResultRepresentation();
if (result.getEffect() == Decision.Effect.DENY) {
rep.setStatus(DecisionEffect.DENY);
} else {
rep.setStatus(DecisionEffect.PERMIT);
}
resultsRep.add(rep);
if (result.getPermission().getResource() != null) {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setId(result.getPermission().getResource().getId());
resource.setName(result.getPermission().getResource().getName());
rep.setResource(resource);
} else {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setName("Any Resource with Scopes " + result.getPermission().getScopes().stream().map(Scope::getName).collect(Collectors.toList()));
rep.setResource(resource);
}
rep.setScopes(result.getPermission().getScopes().stream().map(scope -> {
ScopeRepresentation representation = new ScopeRepresentation();
representation.setId(scope.getId());
representation.setName(scope.getName());
return representation;
}).collect(Collectors.toList()));
List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = new ArrayList<>();
for (Result.PolicyResult policy : result.getResults()) {
PolicyResultRepresentation policyRep = toRepresentation(policy, authorization);
if ("resource".equals(policy.getPolicy().getType())) {
policyRep.getPolicy().setScopes(result.getPermission().getResource().getScopes().stream().map(Scope::getName).collect(Collectors.toSet()));
}
policies.add(policyRep);
}
rep.setPolicies(policies);
}
resultsRep.sort(Comparator.comparing(o -> o.getResource().getName()));
Map<String, PolicyEvaluationResponse.EvaluationResultRepresentation> groupedResults = new HashMap<>();
resultsRep.forEach(evaluationResultRepresentation -> {
PolicyEvaluationResponse.EvaluationResultRepresentation result = groupedResults.get(evaluationResultRepresentation.getResource().getId());
ResourceRepresentation resource = evaluationResultRepresentation.getResource();
if (result == null) {
groupedResults.put(resource.getId(), evaluationResultRepresentation);
result = evaluationResultRepresentation;
}
if (result.getStatus().equals(DecisionEffect.PERMIT) || (evaluationResultRepresentation.getStatus().equals(DecisionEffect.PERMIT) && result.getStatus().equals(DecisionEffect.DENY))) {
result.setStatus(DecisionEffect.PERMIT);
}
List<ScopeRepresentation> scopes = result.getScopes();
if (DecisionEffect.PERMIT.equals(result.getStatus())) {
result.setAllowedScopes(scopes);
}
if (resource.getId() != null) {
if (!scopes.isEmpty()) {
result.getResource().setName(evaluationResultRepresentation.getResource().getName() + " with scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
} else {
result.getResource().setName(evaluationResultRepresentation.getResource().getName());
}
} else {
result.getResource().setName("Any Resource with Scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
}
List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = result.getPolicies();
for (PolicyEvaluationResponse.PolicyResultRepresentation policy : new ArrayList<>(evaluationResultRepresentation.getPolicies())) {
if (!policies.contains(policy)) {
policies.add(policy);
}
}
});
response.setResults(groupedResults.values().stream().collect(Collectors.toList()));
return response;
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class AuthorizationTokenService method resolvePreviousGrantedPermissions.
private void resolvePreviousGrantedPermissions(PermissionTicketToken ticket, KeycloakAuthorizationRequest request, ResourceServer resourceServer, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, ScopeStore scopeStore, AtomicInteger limit) {
AccessToken rpt = request.getRpt();
if (rpt != null && rpt.isActive()) {
Authorization authorizationData = rpt.getAuthorization();
if (authorizationData != null) {
Collection<Permission> permissions = authorizationData.getPermissions();
if (permissions != null) {
for (Permission grantedPermission : permissions) {
if (limit != null && limit.get() <= 0) {
break;
}
Resource resource = resourceStore.findById(grantedPermission.getResourceId(), ticket.getIssuedFor());
if (resource != null) {
ResourcePermission permission = permissionsToEvaluate.get(resource.getId());
if (permission == null) {
permission = new ResourcePermission(resource, new ArrayList<>(), resourceServer, grantedPermission.getClaims());
permissionsToEvaluate.put(resource.getId(), permission);
if (limit != null) {
limit.decrementAndGet();
}
} else {
if (grantedPermission.getClaims() != null) {
for (Entry<String, Set<String>> entry : grantedPermission.getClaims().entrySet()) {
Set<String> claims = permission.getClaims().get(entry.getKey());
if (claims != null) {
claims.addAll(entry.getValue());
}
}
}
}
for (String scopeName : grantedPermission.getScopes()) {
Scope scope = scopeStore.findByName(scopeName, resourceServer.getId());
if (scope != null) {
if (!permission.getScopes().contains(scope)) {
permission.getScopes().add(scope);
}
}
}
}
}
}
}
}
}
Aggregations