Search in sources :

Example 1 with UmaResource

use of io.jans.ca.server.model.UmaResource in project jans by JanssenProject.

the class RsProtectOperation method validate.

private void validate(RsProtectParams params) {
    if (params.getResources() == null || params.getResources().isEmpty()) {
        throw new HttpException(ErrorResponseCode.NO_UMA_RESOURCES_TO_PROTECT);
    }
    if (!ResourceValidator.isHttpMethodUniqueInPath(params.getResources())) {
        throw new HttpException(ErrorResponseCode.UMA_HTTP_METHOD_NOT_UNIQUE);
    }
    if (params.getResources() != null) {
        for (RsResource resource : params.getResources()) {
            if (resource.getConditions() != null) {
                for (Condition condition : resource.getConditions()) {
                    if (condition.getScopeExpression() != null) {
                        String json = condition.getScopeExpression().toString();
                        if (StringUtils.isNotBlank(json) && !json.equalsIgnoreCase("null")) {
                            boolean nodeValid = JsonLogicNodeParser.isNodeValid(json);
                            LOG.trace("Scope expression validator - Valid: " + nodeValid + ", expression: " + json);
                            if (!nodeValid) {
                                throw new HttpException(ErrorResponseCode.UMA_FAILED_TO_VALIDATE_SCOPE_EXPRESSION);
                            }
                            validateScopeExpression(json);
                        }
                    }
                }
            }
        }
    }
    Rp rp = getRp();
    List<UmaResource> existingUmaResources = rp.getUmaProtectedResources();
    if (existingUmaResources != null && !existingUmaResources.isEmpty()) {
        if (params.getOverwrite() == null || !params.getOverwrite()) {
            throw new HttpException(ErrorResponseCode.UMA_PROTECTION_FAILED_BECAUSE_RESOURCES_ALREADY_EXISTS);
        } else {
            // remove existing resources, overwrite=true
            UmaMetadata discovery = getDiscoveryService().getUmaDiscoveryByRpId(params.getRpId());
            String pat = getUmaTokenService().getPat(params.getRpId()).getToken();
            UmaResourceService resourceService = UmaClientFactory.instance().createResourceService(discovery, getHttpService().getClientEngine());
            for (UmaResource resource : existingUmaResources) {
                LOG.trace("Removing existing resource " + resource.getId() + " ...");
                resourceService.deleteResource("Bearer " + pat, resource.getId());
                LOG.trace("Removed existing resource " + resource.getId() + ".");
            }
            rp.getUmaProtectedResources().clear();
            getRpService().updateSilently(rp);
        }
    }
}
Also used : Condition(io.jans.ca.rs.protect.Condition) UmaMetadata(io.jans.as.model.uma.UmaMetadata) RsResource(io.jans.ca.rs.protect.RsResource) UmaResourceService(io.jans.as.client.uma.UmaResourceService) HttpException(io.jans.ca.server.HttpException) Rp(io.jans.ca.server.service.Rp) UmaResource(io.jans.ca.server.model.UmaResource)

Example 2 with UmaResource

use of io.jans.ca.server.model.UmaResource in project jans by JanssenProject.

the class RsProtectOperation method persist.

private void persist(ResourceRegistrar registrar, Rp rp) throws IOException {
    Map<Key, RsResource> resourceMapCopy = registrar.getResourceMapCopy();
    for (Map.Entry<Key, String> entry : registrar.getIdMapCopy().entrySet()) {
        UmaResource resource = new UmaResource();
        resource.setId(entry.getValue());
        resource.setPath(entry.getKey().getPath());
        resource.setHttpMethods(entry.getKey().getHttpMethods());
        Set<String> scopes = Sets.newHashSet();
        Set<String> scopesForTicket = Sets.newHashSet();
        Set<String> scopeExpressions = Sets.newHashSet();
        RsResource rsResource = resourceMapCopy.get(entry.getKey());
        for (String httpMethod : entry.getKey().getHttpMethods()) {
            List<String> rsScopes = rsResource.scopes(httpMethod);
            if (rsScopes != null) {
                scopes.addAll(rsScopes);
            }
            scopesForTicket.addAll(rsResource.getScopesForTicket(httpMethod));
            JsonNode scopeExpression = rsResource.getScopeExpression(httpMethod);
            if (scopeExpression != null) {
                scopeExpressions.add(scopeExpression.toString());
            }
        }
        resource.setScopes(Lists.newArrayList(scopes));
        resource.setTicketScopes(Lists.newArrayList(scopesForTicket));
        resource.setScopeExpressions(Lists.newArrayList(scopeExpressions));
        if (rsResource.getIat() != null && rsResource.getIat() > 0) {
            resource.setIat(rsResource.getIat());
        }
        if (rsResource.getExp() != null && rsResource.getExp() > 0) {
            resource.setExp(rsResource.getExp());
        }
        rp.getUmaProtectedResources().add(resource);
    }
    getRpService().update(rp);
}
Also used : RsResource(io.jans.ca.rs.protect.RsResource) JsonNode(com.fasterxml.jackson.databind.JsonNode) Map(java.util.Map) Key(io.jans.ca.rs.protect.resteasy.Key) UmaResource(io.jans.ca.server.model.UmaResource)

Example 3 with UmaResource

use of io.jans.ca.server.model.UmaResource in project jans by JanssenProject.

the class RsCheckAccessOperation method execute.

@Override
public IOpResponse execute(final RsCheckAccessParams params) throws Exception {
    validate(params);
    Rp rp = getRp();
    UmaResource resource = rp.umaResource(params.getPath(), params.getHttpMethod());
    if (resource == null) {
        final ErrorResponse error = new ErrorResponse("invalid_request");
        error.setErrorDescription("Resource is not protected with path: " + params.getPath() + " and httpMethod: " + params.getHttpMethod() + ". Please protect your resource first with uma_rs_protect command. Check details on " + CoreUtils.DOC_URL);
        LOG.error(error.getErrorDescription());
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(Jackson2.asJson(error)).build());
    }
    PatProvider patProvider = new PatProvider() {

        @Override
        public String getPatToken() {
            return getUmaTokenService().getPat(params.getRpId()).getToken();
        }

        @Override
        public void clearPat() {
        // do nothing
        }
    };
    List<String> requiredScopes = getRequiredScopes(params, resource);
    CorrectRptIntrospectionResponse status = getIntrospectionService().introspectRpt(params.getRpId(), params.getRpt());
    LOG.trace("RPT: " + params.getRpt() + ", status: " + status);
    if (!Strings.isNullOrEmpty(params.getRpt()) && status != null && status.getActive() && status.getPermissions() != null) {
        for (CorrectUmaPermission permission : status.getPermissions()) {
            boolean containsAny = !Collections.disjoint(requiredScopes, permission.getScopes());
            LOG.trace("containsAny: " + containsAny + ", requiredScopes: " + requiredScopes + ", permissionScopes: " + permission.getScopes());
            if (containsAny) {
                if ((permission.getResourceId() != null && permission.getResourceId().equals(resource.getId()))) {
                    // normal UMA
                    LOG.debug("RPT has enough permissions, access GRANTED. Path: " + params.getPath() + ", httpMethod:" + params.getHttpMethod() + ", site: " + rp);
                    return new RsCheckAccessResponse("granted");
                }
            }
        }
    }
    if (CollectionUtils.isEmpty(params.getScopes()) && !CollectionUtils.isEmpty(resource.getTicketScopes())) {
        requiredScopes = resource.getTicketScopes();
    }
    final RptPreProcessInterceptor rptInterceptor = getOpClientFactory().createRptPreProcessInterceptor(new ResourceRegistrar(patProvider, new ServiceProvider(rp.getOpHost())));
    Response response = null;
    try {
        LOG.trace("Try to register ticket, scopes: " + requiredScopes + ", resourceId: " + resource.getId());
        response = rptInterceptor.registerTicketResponse(requiredScopes, resource.getId());
    } catch (ClientErrorException e) {
        LOG.debug("Failed to register ticket. Entity: " + e.getResponse().readEntity(String.class) + ", status: " + e.getResponse().getStatus(), e);
        if (e.getResponse().getStatus() == 400 || e.getResponse().getStatus() == 401) {
            LOG.debug("Try maybe PAT is lost on AS, force refresh PAT and request ticket again ...");
            // force to refresh PAT
            getUmaTokenService().obtainPat(params.getRpId());
            response = rptInterceptor.registerTicketResponse(requiredScopes, resource.getId());
        } else {
            throw e;
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw e;
    }
    RsCheckAccessResponse opResponse = new RsCheckAccessResponse("denied");
    opResponse.setWwwAuthenticateHeader((String) response.getMetadata().getFirst("WWW-Authenticate"));
    opResponse.setTicket(((PermissionTicket) response.getEntity()).getTicket());
    LOG.debug("Access denied for path: " + params.getPath() + " and httpMethod: " + params.getHttpMethod() + ". Ticket is registered: " + opResponse);
    return opResponse;
}
Also used : CorrectRptIntrospectionResponse(io.jans.ca.common.introspection.CorrectRptIntrospectionResponse) WebApplicationException(javax.ws.rs.WebApplicationException) RsCheckAccessResponse(io.jans.ca.common.response.RsCheckAccessResponse) ResourceRegistrar(io.jans.ca.rs.protect.resteasy.ResourceRegistrar) CorrectUmaPermission(io.jans.ca.common.introspection.CorrectUmaPermission) ClientErrorException(javax.ws.rs.ClientErrorException) HttpException(io.jans.ca.server.HttpException) WebApplicationException(javax.ws.rs.WebApplicationException) CorrectRptIntrospectionResponse(io.jans.ca.common.introspection.CorrectRptIntrospectionResponse) IOpResponse(io.jans.ca.common.response.IOpResponse) RsCheckAccessResponse(io.jans.ca.common.response.RsCheckAccessResponse) Response(javax.ws.rs.core.Response) ServiceProvider(io.jans.ca.rs.protect.resteasy.ServiceProvider) PatProvider(io.jans.ca.rs.protect.resteasy.PatProvider) ClientErrorException(javax.ws.rs.ClientErrorException) RptPreProcessInterceptor(io.jans.ca.rs.protect.resteasy.RptPreProcessInterceptor) Rp(io.jans.ca.server.service.Rp) UmaResource(io.jans.ca.server.model.UmaResource)

Example 4 with UmaResource

use of io.jans.ca.server.model.UmaResource in project jans by JanssenProject.

the class Rp method umaResource.

public UmaResource umaResource(String path, String httpMethod) {
    List<UmaResource> copy = Lists.newArrayList(umaProtectedResources);
    Collections.reverse(copy);
    for (UmaResource resource : copy) {
        if (path.equalsIgnoreCase(resource.getPath()) && resource.getHttpMethods() != null) {
            for (String http : resource.getHttpMethods()) {
                if (http.equalsIgnoreCase(httpMethod)) {
                    return resource;
                }
            }
        }
    }
    return null;
}
Also used : UmaResource(io.jans.ca.server.model.UmaResource)

Aggregations

UmaResource (io.jans.ca.server.model.UmaResource)4 RsResource (io.jans.ca.rs.protect.RsResource)2 HttpException (io.jans.ca.server.HttpException)2 Rp (io.jans.ca.server.service.Rp)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 UmaResourceService (io.jans.as.client.uma.UmaResourceService)1 UmaMetadata (io.jans.as.model.uma.UmaMetadata)1 CorrectRptIntrospectionResponse (io.jans.ca.common.introspection.CorrectRptIntrospectionResponse)1 CorrectUmaPermission (io.jans.ca.common.introspection.CorrectUmaPermission)1 IOpResponse (io.jans.ca.common.response.IOpResponse)1 RsCheckAccessResponse (io.jans.ca.common.response.RsCheckAccessResponse)1 Condition (io.jans.ca.rs.protect.Condition)1 Key (io.jans.ca.rs.protect.resteasy.Key)1 PatProvider (io.jans.ca.rs.protect.resteasy.PatProvider)1 ResourceRegistrar (io.jans.ca.rs.protect.resteasy.ResourceRegistrar)1 RptPreProcessInterceptor (io.jans.ca.rs.protect.resteasy.RptPreProcessInterceptor)1 ServiceProvider (io.jans.ca.rs.protect.resteasy.ServiceProvider)1 Map (java.util.Map)1 ClientErrorException (javax.ws.rs.ClientErrorException)1 WebApplicationException (javax.ws.rs.WebApplicationException)1