Java Code Examples for javax.ws.rs.core.Response.Status#FORBIDDEN

The following examples show how to use javax.ws.rs.core.Response.Status#FORBIDDEN . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
protected void validateClusterForTenant(String tenant, String cluster) {
    TenantInfo tenantInfo;
    try {
        tenantInfo = pulsar().getConfigurationCache().propertiesCache().get(path(POLICIES, tenant))
                .orElseThrow(() -> new RestException(Status.NOT_FOUND, "Tenant does not exist"));
    } catch (Exception e) {
        log.error("Failed to get tenant admin data for tenant");
        throw new RestException(e);
    }

    // Check if tenant is allowed on the cluster
    if (!tenantInfo.getAllowedClusters().contains(cluster)) {
        String msg = String.format("Cluster [%s] is not in the list of allowed clusters list for tenant [%s]",
                cluster, tenant);
        log.info(msg);
        throw new RestException(Status.FORBIDDEN, msg);
    }
    log.info("Successfully validated clusters on tenant [{}]", tenant);
}
 
Example 2
Source File: MCRRestAPIUploadHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * deletes a whole derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object 
 * @param pathParamMcrObjID - the MyCoRe Object ID
 * @param pathParamMcrDerID - the MyCoRe Derivate ID
 * @return a Jersey Response Object
 * @throws MCRRestAPIException
 */
public static Response deleteDerivate(UriInfo info, HttpServletRequest request, String pathParamMcrObjID,
    String pathParamMcrDerID) throws MCRRestAPIException {

    MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
    MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);

    try {
        MCRMetadataManager.deleteMCRDerivate(derID);
        return Response
            .created(info.getBaseUriBuilder().path("objects/" + objID + "/derivates").build())
            .type("application/xml; charset=UTF-8")
            .build();
    } catch (MCRAccessException e) {
        throw new MCRRestAPIException(Status.FORBIDDEN,
            new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "Could not delete derivate", e.getMessage()));
    }
}
 
Example 3
Source File: ErrorService.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/add", method = RequestMethod.GET)
public int add(int x, int y) {
  if (x == 99) {
    throw new NullPointerException("un expected NPE test.");
  }
  if (x == 88) {
    ErrorData data = new ErrorData();
    data.setId(12);
    data.setMessage("not allowed id.");
    throw new InvocationException(Status.FORBIDDEN, data);
  }
  if (x == 77) {
    throw new IllegalStateException("77");
  }
  return x + y;
}
 
Example 4
Source File: AdminResource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the broker is allowed to do read-write operations based on the existence of a node in global
 * zookeeper.
 *
 * @throws WebApplicationException
 *             if broker has a read only access if broker is not connected to the global zookeeper
 */
public void validatePoliciesReadOnlyAccess() {
    boolean arePoliciesReadOnly = true;

    try {
        arePoliciesReadOnly = globalZkCache().exists(POLICIES_READONLY_FLAG_PATH);
    } catch (Exception e) {
        log.warn("Unable to fetch contents of [{}] from global zookeeper", POLICIES_READONLY_FLAG_PATH, e);
        throw new RestException(e);
    }

    if (arePoliciesReadOnly) {
        log.debug("Policies are read-only. Broker cannot do read-write operations");
        throw new RestException(Status.FORBIDDEN, "Broker is forbidden to do read-write operations");
    } else {
        // Make sure the broker is connected to the global zookeeper before writing. If not, throw an exception.
        if (globalZkCache().getZooKeeper().getState() != States.CONNECTED) {
            log.debug("Broker is not connected to the global zookeeper");
            throw new RestException(Status.PRECONDITION_FAILED,
                    "Broker needs to be connected to global zookeeper before making a read-write operation");
        } else {
            // Do nothing, just log the message.
            log.debug("Broker is allowed to make read-write operations");
        }
    }
}
 
Example 5
Source File: ShiroExceptionMapper.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(AuthorizationException exception) {

    Status status;

    if (exception instanceof UnauthorizedException) {
        status = Status.FORBIDDEN;
    } else {
        status = Status.UNAUTHORIZED;
    }

    return Response.status(status).build();
}
 
Example 6
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void validateNamespaceOperation(NamespaceName namespaceName, NamespaceOperation operation) {
    if (pulsar().getConfiguration().isAuthenticationEnabled() && pulsar().getBrokerService().isAuthorizationEnabled()) {
        if (!isClientAuthenticated(clientAppId())) {
            throw new RestException(Status.FORBIDDEN, "Need to authenticate to perform the request");
        }

        Boolean isAuthorized = pulsar().getBrokerService().getAuthorizationService()
                .allowNamespaceOperation(namespaceName, operation, originalPrincipal(), clientAppId(), clientAuthData());

        if (!isAuthorized) {
            throw new RestException(Status.FORBIDDEN, String.format("Unauthorized to validateNamespaceOperation for" +
                    " operation [%s] on namespace [%s]", operation.toString(), namespaceName));
        }
    }
}
 
Example 7
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void validateNamespacePolicyOperation(NamespaceName namespaceName, PolicyName policy, PolicyOperation operation) {
    if (pulsar().getConfiguration().isAuthenticationEnabled() && pulsar().getBrokerService().isAuthorizationEnabled()) {
        if (!isClientAuthenticated(clientAppId())) {
            throw new RestException(Status.FORBIDDEN, "Need to authenticate to perform the request");
        }

        Boolean isAuthorized = pulsar().getBrokerService().getAuthorizationService()
                .allowNamespacePolicyOperation(namespaceName, policy, operation, originalPrincipal(), clientAppId(), clientAuthData());

        if (!isAuthorized) {
            throw new RestException(Status.FORBIDDEN, String.format("Unauthorized to validateNamespacePolicyOperation for" +
                    " operation [%s] on namespace [%s] on policy [%s]", operation.toString(), namespaceName, policy.toString()));
        }
    }
}
 
Example 8
Source File: TenantRestServiceImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void createTenant(TenantDto dto) {

    if (getIdentityService().isReadOnly()) {
      throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
    }

    Tenant newTenant = getIdentityService().newTenant(dto.getId());
    dto.update(newTenant);

    getIdentityService().saveTenant(newTenant);
  }
 
Example 9
Source File: PinotSegmentRestletResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Deprecated
@GET
@Path("tables/{tableName}/segments")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get a map from server to segments hosted by the server (deprecated, use 'GET /segments/{tableName}/servers' instead)", notes = "Get a map from server to segments hosted by the server (deprecated, use 'GET /segments/{tableName}/servers' instead)")
public List<Map<String, String>> getServerToSegmentsMapDeprecated1(
    @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName,
    @ApiParam(value = "MUST be null") @QueryParam("state") String stateStr,
    @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr)
    throws JsonProcessingException {
  if (stateStr != null) {
    throw new WebApplicationException("Cannot toggle segment state", Status.FORBIDDEN);
  }

  List<String> tableNamesWithType =
      getExistingTableNamesWithType(tableName, Constants.validateTableType(tableTypeStr));
  List<Map<String, String>> resultList = new ArrayList<>(tableNamesWithType.size());
  for (String tableNameWithType : tableNamesWithType) {
    // NOTE: DO NOT change the format for backward-compatibility
    Map<String, String> resultForTable = new LinkedHashMap<>();
    resultForTable.put("tableName", tableNameWithType);
    resultForTable.put("segments",
        JsonUtils.objectToString(_pinotHelixResourceManager.getServerToSegmentsMap(tableNameWithType)));
    resultList.add(resultForTable);
  }
  return resultList;
}
 
Example 10
Source File: AuthenticationTokenRefreshmentExceptionMapper.java    From jersey-jwt with MIT License 5 votes vote down vote up
@Override
public Response toResponse(AuthenticationTokenRefreshmentException exception) {

    Status status = Status.FORBIDDEN;

    ApiErrorDetails errorDetails = new ApiErrorDetails();
    errorDetails.setStatus(status.getStatusCode());
    errorDetails.setTitle(status.getReasonPhrase());
    errorDetails.setMessage("The authentication token cannot be refreshed.");
    errorDetails.setPath(uriInfo.getAbsolutePath().getPath());

    return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
 
Example 11
Source File: UserManagedPermissionService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void checkRequest(String resourceId, UmaPermissionRepresentation representation) {
    ResourceStore resourceStore = this.authorization.getStoreFactory().getResourceStore();
    Resource resource = resourceStore.findById(resourceId, resourceServer.getId());

    if (resource == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource [" + resourceId + "] cannot be found", Response.Status.BAD_REQUEST);
    }

    if (!resource.getOwner().equals(identity.getId())) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resource owner can access policies for resource [" + resourceId + "]", Status.BAD_REQUEST);
    }

    if (!resource.isOwnerManagedAccess()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resources with owner managed accessed can have policies", Status.BAD_REQUEST);
    }

    if (!resourceServer.isAllowRemoteResourceManagement()) {
        throw new ErrorResponseException(OAuthErrorException.REQUEST_NOT_SUPPORTED, "Remote Resource Management not enabled on resource server [" + resourceServer.getId() + "]", Status.FORBIDDEN);
    }

    if (representation != null) {
        Set<String> resourceScopes = resource.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
        Set<String> scopes = representation.getScopes();

        if (scopes == null || scopes.isEmpty()) {
            scopes = resourceScopes;
            representation.setScopes(scopes);
        }

        if (!resourceScopes.containsAll(scopes)) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST);
        }

        if (representation.getCondition() != null) {
            if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) {
                throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Script upload not supported", Status.BAD_REQUEST);
            }
        }
    }
}
 
Example 12
Source File: TestDefaultHttpClientFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAfterReceiveResponseNullProduceProcessor(@Mocked Invocation invocation,
    @Mocked HttpServletResponseEx responseEx,
    @Mocked OperationMeta operationMeta,
    @Mocked RestOperationMeta swaggerRestOperation) throws Exception {
  CommonExceptionData data = new CommonExceptionData("abcd");
  new Expectations() {
    {
      invocation.getOperationMeta();
      result = operationMeta;
      operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
      result = swaggerRestOperation;
      invocation.findResponseType(403);
      result = SimpleType.constructUnsafe(CommonExceptionData.class);
      responseEx.getStatus();
      result = 403;
      responseEx.getStatusType();
      result = Status.FORBIDDEN;
      responseEx.getBodyBuffer();
      result = Buffer.buffer(JsonUtils.writeValueAsString(data).getBytes());
    }
  };

  Response response = filter.afterReceiveResponse(invocation, responseEx);
  Assert.assertEquals(403, response.getStatusCode());
  Assert.assertEquals("Forbidden", response.getReasonPhrase());
  Assert.assertEquals(InvocationException.class, response.<InvocationException>getResult().getClass());
  InvocationException invocationException = response.getResult();
  Assert.assertEquals(
      403,
      invocationException.getStatusCode());
  Assert.assertEquals(
      "CommonExceptionData [message=abcd]",
      invocationException.getErrorData().toString());
}
 
Example 13
Source File: AuthenticationTokenRefreshmentExceptionMapper.java    From jersey-jwt-springsecurity with MIT License 5 votes vote down vote up
@Override
public Response toResponse(AuthenticationTokenRefreshmentException exception) {

    Status status = Status.FORBIDDEN;

    ApiErrorDetails errorDetails = new ApiErrorDetails();
    errorDetails.setStatus(status.getStatusCode());
    errorDetails.setTitle(status.getReasonPhrase());
    errorDetails.setMessage("The authentication token cannot be refreshed.");
    errorDetails.setPath(uriInfo.getAbsolutePath().getPath());

    return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
 
Example 14
Source File: AuthenticationExceptionMapper.java    From jersey-jwt-springsecurity with MIT License 5 votes vote down vote up
@Override
public Response toResponse(AuthenticationException exception) {

    Status status = Status.FORBIDDEN;

    ApiErrorDetails errorDetails = new ApiErrorDetails();
    errorDetails.setStatus(status.getStatusCode());
    errorDetails.setTitle(status.getReasonPhrase());
    errorDetails.setMessage(exception.getMessage());
    errorDetails.setPath(uriInfo.getAbsolutePath().getPath());

    return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
 
Example 15
Source File: ProtectionService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakIdentity createIdentity(boolean checkProtectionScope) {
    KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
    ResourceServer resourceServer = getResourceServer(identity);
    KeycloakSession keycloakSession = authorization.getKeycloakSession();
    RealmModel realm = keycloakSession.getContext().getRealm();
    ClientModel client = realm.getClientById(resourceServer.getId());

    if (checkProtectionScope) {
        if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_SCOPE, "Requires uma_protection scope.", Status.FORBIDDEN);
        }
    }

    return identity;
}
 
Example 16
Source File: AccessDeniedExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.FORBIDDEN;
}
 
Example 17
Source File: AccessDeniedExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.FORBIDDEN;
}
 
Example 18
Source File: UnsupportedExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.FORBIDDEN;
}
 
Example 19
Source File: ForbiddenException.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public ForbiddenException(String msg) {
  super(new Exception(msg), Status.FORBIDDEN);
}
 
Example 20
Source File: SpringAccessDeniedExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.FORBIDDEN;
}