use of org.keycloak.authorization.model.ResourceServer in project keycloak by keycloak.
the class ClientTokenExchangeTest method addDirectExchanger.
private static void addDirectExchanger(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(TEST);
RoleModel exampleRole = realm.addRole("example");
AdminPermissionManagement management = AdminPermissions.management(session, realm);
ClientModel target = realm.addClient("target");
target.setName("target");
target.setClientId("target");
target.setDirectAccessGrantsEnabled(true);
target.setEnabled(true);
target.setSecret("secret");
target.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
target.setFullScopeAllowed(false);
target.addScopeMapping(exampleRole);
ClientModel directExchanger = realm.addClient("direct-exchanger");
directExchanger.setName("direct-exchanger");
directExchanger.setClientId("direct-exchanger");
directExchanger.setPublicClient(false);
directExchanger.setDirectAccessGrantsEnabled(true);
directExchanger.setEnabled(true);
directExchanger.setSecret("secret");
directExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
directExchanger.setFullScopeAllowed(false);
// permission for client to client exchange to "target" client
management.clients().setPermissionsEnabled(target, true);
ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
clientImpersonateRep.setName("clientImpersonatorsDirect");
clientImpersonateRep.addClient(directExchanger.getId());
ResourceServer server = management.realmResourceServer();
Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
management.users().setPermissionsEnabled(true);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
impersonatedUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password"));
impersonatedUser.grantRole(exampleRole);
}
use of org.keycloak.authorization.model.ResourceServer in project keycloak by keycloak.
the class MigrateTo2_1_0 method migrateRolePolicies.
// KEYCLOAK-3338: Changes to how role policy config is stored"
private void migrateRolePolicies(RealmModel realm, KeycloakSession session) {
AuthorizationProvider authorizationProvider = session.getProvider(AuthorizationProvider.class);
StoreFactory storeFactory = authorizationProvider.getStoreFactory();
PolicyStore policyStore = storeFactory.getPolicyStore();
realm.getClientsStream().forEach(clientModel -> {
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
if (resourceServer != null) {
policyStore.findByType("role", resourceServer.getId()).forEach(policy -> {
Map<String, String> config = new HashMap(policy.getConfig());
String roles = config.get("roles");
List roleConfig;
try {
roleConfig = JsonSerialization.readValue(roles, List.class);
} catch (Exception e) {
throw new RuntimeException("Malformed configuration for role policy [" + policy.getName() + "].", e);
}
if (!roleConfig.isEmpty() && roleConfig.get(0) instanceof String) {
try {
config.put("roles", JsonSerialization.writeValueAsString(roleConfig.stream().map(new Function<String, Map>() {
@Override
public Map apply(String roleId) {
Map updated = new HashMap();
updated.put("id", roleId);
return updated;
}
}).collect(Collectors.toList())));
policy.setConfig(config);
} catch (Exception e) {
throw new RuntimeException("Failed to migrate role policy [" + policy.getName() + "].", e);
}
}
});
}
});
}
use of org.keycloak.authorization.model.ResourceServer 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.authorization.model.ResourceServer in project keycloak by keycloak.
the class PolicyEvaluationService method createPermissions.
private List<ResourcePermission> createPermissions(PolicyEvaluationRequest representation, EvaluationContext evaluationContext, AuthorizationProvider authorization, AuthorizationRequest request) {
return representation.getResources().stream().flatMap((Function<ResourceRepresentation, Stream<ResourcePermission>>) resource -> {
StoreFactory storeFactory = authorization.getStoreFactory();
if (resource == null) {
resource = new ResourceRepresentation();
}
Set<ScopeRepresentation> givenScopes = resource.getScopes();
if (givenScopes == null) {
givenScopes = new HashSet<>();
}
ScopeStore scopeStore = storeFactory.getScopeStore();
Set<Scope> scopes = givenScopes.stream().map(scopeRepresentation -> scopeStore.findByName(scopeRepresentation.getName(), resourceServer.getId())).collect(Collectors.toSet());
if (resource.getId() != null) {
Resource resourceModel = storeFactory.getResourceStore().findById(resource.getId(), resourceServer.getId());
return new ArrayList<>(Arrays.asList(Permissions.createResourcePermissions(resourceModel, resourceServer, scopes, authorization, request))).stream();
} else if (resource.getType() != null) {
return storeFactory.getResourceStore().findByType(resource.getType(), resourceServer.getId()).stream().map(resource1 -> Permissions.createResourcePermissions(resource1, resourceServer, scopes, authorization, request));
} else {
if (scopes.isEmpty()) {
return Stream.empty();
}
List<Resource> resources = storeFactory.getResourceStore().findByScope(scopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId());
if (resources.isEmpty()) {
return scopes.stream().map(scope -> new ResourcePermission(null, new ArrayList<>(Arrays.asList(scope)), resourceServer));
}
return resources.stream().map(resource12 -> Permissions.createResourcePermissions(resource12, resourceServer, scopes, authorization, request));
}
}).collect(Collectors.toList());
}
use of org.keycloak.authorization.model.ResourceServer in project keycloak by keycloak.
the class AuthorizationTokenService method authorize.
public Response authorize(KeycloakAuthorizationRequest request) {
EventBuilder event = request.getEvent();
// it is not secure to allow public clients to push arbitrary claims because message can be tampered
if (isPublicClientRequestingEntitlementWithClaims(request)) {
CorsErrorResponseException forbiddenClientException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_GRANT, "Public clients are not allowed to send claims", Status.FORBIDDEN);
fireErrorEvent(event, Errors.INVALID_REQUEST, forbiddenClientException);
throw forbiddenClientException;
}
try {
PermissionTicketToken ticket = getPermissionTicket(request);
request.setClaims(ticket.getClaims());
EvaluationContext evaluationContext = createEvaluationContext(request);
KeycloakIdentity identity = KeycloakIdentity.class.cast(evaluationContext.getIdentity());
if (identity != null) {
event.user(identity.getId());
}
ResourceServer resourceServer = getResourceServer(ticket, request);
Collection<Permission> permissions;
if (request.getTicket() != null) {
permissions = evaluateUserManagedPermissions(request, ticket, resourceServer, evaluationContext);
} else if (ticket.getPermissions().isEmpty() && request.getRpt() == null) {
permissions = evaluateAllPermissions(request, resourceServer, evaluationContext);
} else {
permissions = evaluatePermissions(request, ticket, resourceServer, evaluationContext, identity);
}
if (isGranted(ticket, request, permissions)) {
AuthorizationProvider authorization = request.getAuthorization();
ClientModel targetClient = authorization.getRealm().getClientById(resourceServer.getId());
Metadata metadata = request.getMetadata();
String responseMode = metadata != null ? metadata.getResponseMode() : null;
if (responseMode != null) {
if (RESPONSE_MODE_DECISION.equals(metadata.getResponseMode())) {
Map<String, Object> responseClaims = new HashMap<>();
responseClaims.put(RESPONSE_MODE_DECISION_RESULT, true);
return createSuccessfulResponse(responseClaims, request);
} else if (RESPONSE_MODE_PERMISSIONS.equals(metadata.getResponseMode())) {
return createSuccessfulResponse(permissions, request);
} else {
CorsErrorResponseException invalidResponseModeException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "Invalid response_mode", Status.BAD_REQUEST);
fireErrorEvent(event, Errors.INVALID_REQUEST, invalidResponseModeException);
throw invalidResponseModeException;
}
} else {
return createSuccessfulResponse(createAuthorizationResponse(identity, permissions, request, targetClient), request);
}
}
if (request.isSubmitRequest()) {
CorsErrorResponseException submittedRequestException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.ACCESS_DENIED, "request_submitted", Status.FORBIDDEN);
fireErrorEvent(event, Errors.ACCESS_DENIED, submittedRequestException);
throw submittedRequestException;
} else {
CorsErrorResponseException notAuthorizedException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.ACCESS_DENIED, "not_authorized", Status.FORBIDDEN);
fireErrorEvent(event, Errors.ACCESS_DENIED, notAuthorizedException);
throw notAuthorizedException;
}
} catch (ErrorResponseException | CorsErrorResponseException cause) {
if (logger.isDebugEnabled()) {
logger.debug("Error while evaluating permissions", cause);
}
throw cause;
} catch (Exception cause) {
logger.error("Unexpected error while evaluating permissions", cause);
throw new CorsErrorResponseException(request.getCors(), OAuthErrorException.SERVER_ERROR, "Unexpected error while evaluating permissions", Status.INTERNAL_SERVER_ERROR);
}
}
Aggregations