Merge pull request #4197 from pedroigor/KEYCLOAK-4987

[KEYCLOAK-4987] - Remove async support from AuthZ Token Endpoints
This commit is contained in:
Pedro Igor 2017-05-30 12:49:19 -03:00 committed by GitHub
commit b71bb96540
7 changed files with 106 additions and 155 deletions

View file

@ -1,38 +0,0 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.authorization.permission.evaluator;
import org.keycloak.authorization.Decision;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
* @see PermissionEvaluator
*/
class DefaultPermissionEvaluator implements PermissionEvaluator {
private final PermissionEvaluator publisher;
DefaultPermissionEvaluator(PermissionEvaluator publisher) {
this.publisher = publisher;
}
@Override
public void evaluate(Decision decision) {
publisher.evaluate(decision);
}
}

View file

@ -42,6 +42,6 @@ public final class Evaluators {
} }
public PermissionEvaluator schedule(List<ResourcePermission> permissions, EvaluationContext evaluationContext) { public PermissionEvaluator schedule(List<ResourcePermission> permissions, EvaluationContext evaluationContext) {
return new DefaultPermissionEvaluator(new IterablePermissionEvaluator(permissions.iterator(), evaluationContext, this.policyEvaluator)); return new IterablePermissionEvaluator(permissions.iterator(), evaluationContext, this.policyEvaluator);
} }
} }

View file

@ -17,12 +17,16 @@
*/ */
package org.keycloak.authorization.permission.evaluator; package org.keycloak.authorization.permission.evaluator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.keycloak.authorization.Decision; import org.keycloak.authorization.Decision;
import org.keycloak.authorization.permission.ResourcePermission; import org.keycloak.authorization.permission.ResourcePermission;
import org.keycloak.authorization.policy.evaluation.DecisionResultCollector;
import org.keycloak.authorization.policy.evaluation.EvaluationContext; import org.keycloak.authorization.policy.evaluation.EvaluationContext;
import org.keycloak.authorization.policy.evaluation.PolicyEvaluator; import org.keycloak.authorization.policy.evaluation.PolicyEvaluator;
import org.keycloak.authorization.policy.evaluation.Result;
import java.util.Iterator;
/** /**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
@ -50,4 +54,23 @@ class IterablePermissionEvaluator implements PermissionEvaluator {
decision.onError(cause); decision.onError(cause);
} }
} }
@Override
public List<Result> evaluate() {
AtomicReference<List<Result>> result = new AtomicReference<>();
evaluate(new DecisionResultCollector() {
@Override
public void onError(Throwable cause) {
throw new RuntimeException("Failed to evaluate permissions", cause);
}
@Override
protected void onComplete(List<Result> results) {
result.set(results);
}
});
return result.get();
}
} }

View file

@ -17,7 +17,10 @@
*/ */
package org.keycloak.authorization.permission.evaluator; package org.keycloak.authorization.permission.evaluator;
import java.util.List;
import org.keycloak.authorization.Decision; import org.keycloak.authorization.Decision;
import org.keycloak.authorization.policy.evaluation.Result;
/** /**
* An {@link PermissionEvaluator} represents a source of {@link org.keycloak.authorization.permission.ResourcePermission}, responsible for emitting these permissions * An {@link PermissionEvaluator} represents a source of {@link org.keycloak.authorization.permission.ResourcePermission}, responsible for emitting these permissions
@ -28,4 +31,5 @@ import org.keycloak.authorization.Decision;
public interface PermissionEvaluator { public interface PermissionEvaluator {
void evaluate(Decision decision); void evaluate(Decision decision);
List<Result> evaluate();
} }

View file

@ -35,12 +35,11 @@ import javax.ws.rs.POST;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.OAuthErrorException;
import org.keycloak.authorization.AuthorizationProvider; import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.util.Permissions;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.representations.idm.authorization.PolicyEvaluationRequest;
import org.keycloak.authorization.admin.representation.PolicyEvaluationResponseBuilder; import org.keycloak.authorization.admin.representation.PolicyEvaluationResponseBuilder;
import org.keycloak.authorization.attribute.Attributes; import org.keycloak.authorization.attribute.Attributes;
import org.keycloak.authorization.common.KeycloakEvaluationContext; import org.keycloak.authorization.common.KeycloakEvaluationContext;
@ -54,6 +53,7 @@ import org.keycloak.authorization.policy.evaluation.EvaluationContext;
import org.keycloak.authorization.policy.evaluation.Result; import org.keycloak.authorization.policy.evaluation.Result;
import org.keycloak.authorization.store.ScopeStore; import org.keycloak.authorization.store.ScopeStore;
import org.keycloak.authorization.store.StoreFactory; import org.keycloak.authorization.store.StoreFactory;
import org.keycloak.authorization.util.Permissions;
import org.keycloak.models.AuthenticatedClientSessionModel; import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
@ -61,13 +61,14 @@ import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel; import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel; import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.ProtocolMapper; import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenMapper; import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.authorization.PolicyEvaluationRequest;
import org.keycloak.representations.idm.authorization.ResourceRepresentation; import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ScopeRepresentation; import org.keycloak.representations.idm.authorization.ScopeRepresentation;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.Urls; import org.keycloak.services.Urls;
import org.keycloak.services.managers.AuthenticationManager; import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.resources.admin.RealmAuth; import org.keycloak.services.resources.admin.RealmAuth;
@ -120,18 +121,18 @@ public class PolicyEvaluationService {
this.auth.requireView(); this.auth.requireView();
CloseableKeycloakIdentity identity = createIdentity(evaluationRequest); CloseableKeycloakIdentity identity = createIdentity(evaluationRequest);
try { try {
EvaluationContext evaluationContext = createEvaluationContext(evaluationRequest, identity); return Response.ok(PolicyEvaluationResponseBuilder.build(evaluate(evaluationRequest, createEvaluationContext(evaluationRequest, identity)), resourceServer, authorization, identity)).build();
Decision decisionCollector = new Decision(); } catch (Exception e) {
authorization.evaluators().from(createPermissions(evaluationRequest, evaluationContext, authorization), evaluationContext).evaluate(decisionCollector); throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Error while evaluating permissions.", Status.INTERNAL_SERVER_ERROR);
if (decisionCollector.error != null) {
throw decisionCollector.error;
}
return Response.ok(PolicyEvaluationResponseBuilder.build(decisionCollector.results, resourceServer, authorization, identity)).build();
} finally { } finally {
identity.close(); identity.close();
} }
} }
private List<Result> evaluate(PolicyEvaluationRequest evaluationRequest, EvaluationContext evaluationContext) {
return authorization.evaluators().from(createPermissions(evaluationRequest, evaluationContext, authorization), evaluationContext).evaluate();
}
private EvaluationContext createEvaluationContext(PolicyEvaluationRequest representation, KeycloakIdentity identity) { private EvaluationContext createEvaluationContext(PolicyEvaluationRequest representation, KeycloakIdentity identity) {
return new KeycloakEvaluationContext(identity, this.authorization.getKeycloakSession()) { return new KeycloakEvaluationContext(identity, this.authorization.getKeycloakSession()) {
@Override @Override

View file

@ -25,11 +25,11 @@ import org.keycloak.authorization.authorization.representation.AuthorizationRequ
import org.keycloak.authorization.authorization.representation.AuthorizationResponse; import org.keycloak.authorization.authorization.representation.AuthorizationResponse;
import org.keycloak.authorization.common.KeycloakEvaluationContext; import org.keycloak.authorization.common.KeycloakEvaluationContext;
import org.keycloak.authorization.common.KeycloakIdentity; import org.keycloak.authorization.common.KeycloakIdentity;
import org.keycloak.authorization.entitlement.representation.EntitlementResponse;
import org.keycloak.authorization.model.Resource; import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer; import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope; import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.permission.ResourcePermission; import org.keycloak.authorization.permission.ResourcePermission;
import org.keycloak.authorization.policy.evaluation.DecisionResultCollector;
import org.keycloak.authorization.policy.evaluation.Result; import org.keycloak.authorization.policy.evaluation.Result;
import org.keycloak.authorization.protection.permission.PermissionTicket; import org.keycloak.authorization.protection.permission.PermissionTicket;
import org.keycloak.authorization.store.ResourceStore; import org.keycloak.authorization.store.ResourceStore;
@ -47,14 +47,11 @@ import org.keycloak.representations.idm.authorization.Permission;
import org.keycloak.representations.idm.authorization.ScopeRepresentation; import org.keycloak.representations.idm.authorization.ScopeRepresentation;
import org.keycloak.services.ErrorResponseException; import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.resources.Cors; import org.keycloak.services.resources.Cors;
import org.keycloak.services.resources.RealmsResource;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.OPTIONS; import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
@ -97,7 +94,7 @@ public class AuthorizationTokenService {
@POST @POST
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public void authorize(AuthorizationRequest authorizationRequest, @Suspended AsyncResponse asyncResponse) { public Response authorize(AuthorizationRequest authorizationRequest) {
KeycloakEvaluationContext evaluationContext = new KeycloakEvaluationContext(this.authorization.getKeycloakSession()); KeycloakEvaluationContext evaluationContext = new KeycloakEvaluationContext(this.authorization.getKeycloakSession());
KeycloakIdentity identity = (KeycloakIdentity) evaluationContext.getIdentity(); KeycloakIdentity identity = (KeycloakIdentity) evaluationContext.getIdentity();
@ -109,40 +106,40 @@ public class AuthorizationTokenService {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authorization request.", Status.BAD_REQUEST); throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authorization request.", Status.BAD_REQUEST);
} }
try {
PermissionTicket ticket = verifyPermissionTicket(authorizationRequest); PermissionTicket ticket = verifyPermissionTicket(authorizationRequest);
List<Result> result = authorization.evaluators().from(createPermissions(ticket, authorizationRequest, authorization), evaluationContext).evaluate();
List<Permission> entitlements = Permissions.permits(result, authorization, ticket.getResourceServerId());
authorization.evaluators().from(createPermissions(ticket, authorizationRequest, authorization), evaluationContext).evaluate(new DecisionResultCollector() { if (!entitlements.isEmpty()) {
@Override AuthorizationResponse response = new AuthorizationResponse(createRequestingPartyToken(entitlements, identity.getAccessToken()));
public void onComplete(List<Result> results) { return Cors.add(httpRequest, Response.status(Status.CREATED).entity(response)).allowedOrigins(identity.getAccessToken())
List<Permission> entitlements = Permissions.permits(results, authorization, ticket.getResourceServerId()); .allowedMethods("POST")
.exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
}
} catch (Exception cause) {
logger.error(cause);
throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Error while evaluating permissions.", Status.INTERNAL_SERVER_ERROR);
}
if (entitlements.isEmpty()) {
HashMap<Object, Object> error = new HashMap<>(); HashMap<Object, Object> error = new HashMap<>();
error.put(OAuth2Constants.ERROR, "not_authorized"); error.put(OAuth2Constants.ERROR, "not_authorized");
asyncResponse.resume(Cors.add(httpRequest, Response.status(Status.FORBIDDEN) return Cors.add(httpRequest, Response.status(Status.FORBIDDEN)
.entity(error)) .entity(error))
.allowedOrigins(identity.getAccessToken()) .allowedOrigins(identity.getAccessToken())
.exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build()); .exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
} else {
AuthorizationResponse response = new AuthorizationResponse(createRequestingPartyToken(entitlements, identity.getAccessToken()));
asyncResponse.resume(Cors.add(httpRequest, Response.status(Status.CREATED).entity(response)).allowedOrigins(identity.getAccessToken())
.allowedMethods("POST")
.exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build());
}
}
@Override
public void onError(Throwable cause) {
logger.error("failed authorize", cause);
asyncResponse.resume(cause);
}
});
} }
private List<ResourcePermission> createPermissions(PermissionTicket ticket, AuthorizationRequest request, AuthorizationProvider authorization) { private List<ResourcePermission> createPermissions(PermissionTicket ticket, AuthorizationRequest request, AuthorizationProvider authorization) {
StoreFactory storeFactory = authorization.getStoreFactory(); StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findById(ticket.getResourceServerId());
if (resourceServer == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client does not support permissions", Status.FORBIDDEN);
}
Map<String, Set<String>> permissionsToEvaluate = new HashMap<>(); Map<String, Set<String>> permissionsToEvaluate = new HashMap<>();
ticket.getResources().forEach(requestedResource -> { ticket.getResources().forEach(requestedResource -> {
@ -231,8 +228,6 @@ public class AuthorizationTokenService {
} }
} }
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findById(ticket.getResourceServerId());
return permissionsToEvaluate.entrySet().stream() return permissionsToEvaluate.entrySet().stream()
.flatMap((Function<Entry<String, Set<String>>, Stream<ResourcePermission>>) entry -> { .flatMap((Function<Entry<String, Set<String>>, Stream<ResourcePermission>>) entry -> {
String key = entry.getKey(); String key = entry.getKey();

View file

@ -26,7 +26,6 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -37,8 +36,6 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
@ -48,7 +45,6 @@ import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.OAuth2Constants; import org.keycloak.OAuth2Constants;
import org.keycloak.OAuthErrorException; import org.keycloak.OAuthErrorException;
import org.keycloak.authorization.AuthorizationProvider; import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.authorization.AuthorizationTokenService;
import org.keycloak.authorization.common.KeycloakEvaluationContext; import org.keycloak.authorization.common.KeycloakEvaluationContext;
import org.keycloak.authorization.common.KeycloakIdentity; import org.keycloak.authorization.common.KeycloakIdentity;
import org.keycloak.authorization.entitlement.representation.EntitlementRequest; import org.keycloak.authorization.entitlement.representation.EntitlementRequest;
@ -57,7 +53,6 @@ import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer; import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope; import org.keycloak.authorization.model.Scope;
import org.keycloak.authorization.permission.ResourcePermission; import org.keycloak.authorization.permission.ResourcePermission;
import org.keycloak.authorization.policy.evaluation.DecisionResultCollector;
import org.keycloak.authorization.policy.evaluation.Result; import org.keycloak.authorization.policy.evaluation.Result;
import org.keycloak.authorization.store.ResourceStore; import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.authorization.store.ScopeStore; import org.keycloak.authorization.store.ScopeStore;
@ -74,7 +69,6 @@ import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.authorization.Permission; import org.keycloak.representations.idm.authorization.Permission;
import org.keycloak.representations.idm.authorization.ScopeRepresentation; import org.keycloak.representations.idm.authorization.ScopeRepresentation;
import org.keycloak.services.ErrorResponse;
import org.keycloak.services.ErrorResponseException; import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.resources.Cors; import org.keycloak.services.resources.Cors;
@ -106,7 +100,7 @@ public class EntitlementService {
@GET() @GET()
@Produces("application/json") @Produces("application/json")
@Consumes("application/json") @Consumes("application/json")
public void getAll(@PathParam("resource_server_id") String resourceServerId, @Suspended AsyncResponse asyncResponse) { public Response getAll(@PathParam("resource_server_id") String resourceServerId) {
KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession()); KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
if (resourceServerId == null) { if (resourceServerId == null) {
@ -123,39 +117,18 @@ public class EntitlementService {
StoreFactory storeFactory = authorization.getStoreFactory(); StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(client.getId()); ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(client.getId());
authorization.evaluators().from(Permissions.all(resourceServer, identity, authorization), new KeycloakEvaluationContext(this.authorization.getKeycloakSession())).evaluate(new DecisionResultCollector() { if (resourceServer == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client does not support permissions", Status.FORBIDDEN);
@Override
public void onError(Throwable cause) {
logger.error("failed", cause);
asyncResponse.resume(cause);
} }
@Override return evaluate(Permissions.all(resourceServer, identity, authorization), identity, resourceServer);
protected void onComplete(List<Result> results) {
List<Permission> entitlements = Permissions.permits(results, authorization, resourceServer.getId());
if (entitlements.isEmpty()) {
HashMap<Object, Object> error = new HashMap<>();
error.put(OAuth2Constants.ERROR, "not_authorized");
asyncResponse.resume(Cors.add(request, Response.status(Status.FORBIDDEN)
.entity(error))
.allowedOrigins(identity.getAccessToken())
.exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build());
} else {
asyncResponse.resume(Cors.add(request, Response.ok().entity(new EntitlementResponse(createRequestingPartyToken(entitlements, identity.getAccessToken())))).allowedOrigins(identity.getAccessToken()).allowedMethods("GET").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build());
}
}
});
} }
@Path("{resource_server_id}") @Path("{resource_server_id}")
@POST @POST
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public void get(@PathParam("resource_server_id") String resourceServerId, EntitlementRequest entitlementRequest, @Suspended AsyncResponse asyncResponse) { public Response get(@PathParam("resource_server_id") String resourceServerId, EntitlementRequest entitlementRequest) {
KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession()); KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
if (entitlementRequest == null) { if (entitlementRequest == null) {
@ -177,41 +150,34 @@ public class EntitlementService {
StoreFactory storeFactory = authorization.getStoreFactory(); StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(client.getId()); ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(client.getId());
try { if (resourceServer == null) {
authorization.evaluators().from(createPermissions(entitlementRequest, resourceServer, authorization), new KeycloakEvaluationContext(this.authorization.getKeycloakSession())).evaluate(new DecisionResultCollector() { throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client does not support permissions", Status.FORBIDDEN);
@Override
public void onError(Throwable cause) {
logger.error("failed", cause);
asyncResponse.resume(cause);
} }
@Override return evaluate(createPermissions(entitlementRequest, resourceServer, authorization), identity, resourceServer);
protected void onComplete(List<Result> results) { }
List<Permission> entitlements = Permissions.permits(results, authorization, resourceServer.getId());
private Response evaluate(List<ResourcePermission> permissions, KeycloakIdentity identity, ResourceServer resourceServer) {
try {
List<Result> result = authorization.evaluators().from(permissions, new KeycloakEvaluationContext(this.authorization.getKeycloakSession())).evaluate();
List<Permission> entitlements = Permissions.permits(result, authorization, resourceServer.getId());
if (!entitlements.isEmpty()) {
return Cors.add(request, Response.ok().entity(new EntitlementResponse(createRequestingPartyToken(entitlements, identity.getAccessToken())))).allowedOrigins(identity.getAccessToken()).allowedMethods("GET").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
}
} catch (Exception cause) {
logger.error(cause);
throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Error while evaluating permissions.", Status.INTERNAL_SERVER_ERROR);
}
if (entitlements.isEmpty()) {
HashMap<Object, Object> error = new HashMap<>(); HashMap<Object, Object> error = new HashMap<>();
error.put(OAuth2Constants.ERROR, "not_authorized"); error.put(OAuth2Constants.ERROR, "not_authorized");
asyncResponse.resume(Cors.add(request, Response.status(Status.FORBIDDEN) return Cors.add(request, Response.status(Status.FORBIDDEN)
.entity(error)) .entity(error))
.allowedOrigins(identity.getAccessToken()) .allowedOrigins(identity.getAccessToken())
.exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build()); .exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
} else {
asyncResponse.resume(Cors.add(request, Response.ok().entity(new EntitlementResponse(createRequestingPartyToken(entitlements, identity.getAccessToken())))).allowedOrigins(identity.getAccessToken()).allowedMethods("GET").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build());
}
}
});
} catch (Exception e) {
String message = e.getMessage();
if (message == null) {
message = "Could not process authorization request";
}
asyncResponse.resume(ErrorResponse.error(message, Status.BAD_REQUEST));
}
} }
private String createRequestingPartyToken(List<Permission> permissions, AccessToken accessToken) { private String createRequestingPartyToken(List<Permission> permissions, AccessToken accessToken) {