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

The following examples show how to use javax.ws.rs.core.Response.Status#UNAUTHORIZED . 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: WebSocketWebResource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a caller id (IP + role)
 *
 * @return the web service caller identification
 */
public String clientAppId() {
    if (isBlank(clientId)) {
        try {
            clientId = service().getAuthenticationService().authenticateHttpRequest(httpRequest);
        } catch (AuthenticationException e) {
            if (service().getConfig().isAuthenticationEnabled()) {
                throw new RestException(Status.UNAUTHORIZED, "Failed to get clientId from request");
            }
        }

        if (isBlank(clientId) && service().getConfig().isAuthenticationEnabled()) {
            throw new RestException(Status.UNAUTHORIZED, "Failed to get auth data from the request");
        }
    }
    return clientId;
}
 
Example 2
Source File: PersistentTopicsBase.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private void validateAdminAccessForSubscriber(String subscriptionName) {
    try {
        if (!pulsar().getBrokerService().getAuthorizationService().canConsume(topicName, clientAppId(),
                clientAuthData(), subscriptionName)) {
            log.warn("[{}} Subscriber {} is not authorized to access api", topicName, clientAppId());
            throw new RestException(Status.UNAUTHORIZED,
                    String.format("Subscriber %s is not authorized to access this operation", clientAppId()));
        }
    } catch (RestException re) {
        throw re;
    } catch (Exception e) {
        // unknown error marked as internal server error
        log.warn("Unexpected error while authorizing request. topic={}, role={}. Error: {}", topicName,
                clientAppId(), e.getMessage(), e);
        throw new RestException(e);
    }
}
 
Example 3
Source File: WebSocketWebResource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if user has super-user access or user is authorized to produce/consume on a given topic
 *
 * @param topic
 * @throws RestException
 */
protected void validateUserAccess(TopicName topic) {
    boolean isAuthorized = false;

    try {
        validateSuperUserAccess();
        isAuthorized = true;
    } catch (Exception e) {
        try {
            isAuthorized = isAuthorized(topic);
        } catch (Exception ne) {
            throw new RestException(ne);
        }
    }

    if (!isAuthorized) {
        throw new RestException(Status.UNAUTHORIZED, "Don't have permission to access this topic");
    }
}
 
Example 4
Source File: WorkerImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public WorkerInfo getClusterLeader(String clientRole) {
    if (!isWorkerServiceAvailable()) {
        throwUnavailableException();
    }

    if (worker().getWorkerConfig().isAuthorizationEnabled() && !isSuperUser(clientRole)) {
        log.error("Client [{}] is not authorized to get cluster leader", clientRole);
        throw new RestException(Status.UNAUTHORIZED, "client is not authorize to perform operation");
    }

    MembershipManager membershipManager = worker().getMembershipManager();
    WorkerInfo leader = membershipManager.getLeader();

    if (leader == null) {
        throw new RestException(Status.INTERNAL_SERVER_ERROR, "Leader cannot be determined");
    }

    return leader;
}
 
Example 5
Source File: LoginRestApi.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@POST
@Path("logout")
@ZeppelinApi
public Response logout() {
  logoutCurrentUser();
  Status status;
  Map<String, String> data = new HashMap<>();
  if (zConf.isAuthorizationHeaderClear()) {
    status = Status.UNAUTHORIZED;
    data.put("clearAuthorizationHeader", "true");
  } else {
    status = Status.FORBIDDEN;
    data.put("clearAuthorizationHeader", "false");
  }
  if (isKnoxSSOEnabled()) {
    KnoxJwtRealm knoxJwtRealm = getJTWRealm();
    data.put("redirectURL", constructKnoxUrl(knoxJwtRealm, knoxJwtRealm.getLogout()));
    data.put("isLogoutAPI", knoxJwtRealm.getLogoutAPI().toString());
  }
  JsonResponse<Map<String, String>> response = new JsonResponse<>(status, "", data);
  LOG.info(response.toString());
  return response.build();
}
 
Example 6
Source File: MCRIViewZipResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Zips a derivate and its containing iview images as jpg's. All other files are ignored.
 * 
 * @param derivateID the derivate to zip
 * @param zoom if undefined the base resolution is assumed
 * @return zip file
 */
@GET
@Produces("application/zip")
@Path("{derivateID}")
public Response zip(@PathParam("derivateID") String derivateID, @QueryParam("zoom") Integer zoom) throws Exception {
    if (!MCRAccessManager.checkDerivateContentPermission(MCRObjectID.getInstance(derivateID),
        MCRAccessManager.PERMISSION_READ)) {
        throw new WebApplicationException(Status.UNAUTHORIZED);
    }
    MCRPath derivateRoot = MCRPath.getPath(derivateID, "/");
    if (!Files.exists(derivateRoot)) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    ZipStreamingOutput stream = new ZipStreamingOutput(derivateRoot, zoom);
    return Response.ok(stream).header("Content-Disposition", "attachnment; filename=\"" + derivateID + ".zip\"")
        .build();
}
 
Example 7
Source File: ShiroExceptionHandler.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response toResponse(ShiroException exception) {

    Status status = Status.FORBIDDEN; // Invalid api key
    if (exception instanceof AccountException) {
        // API key missing
        status = Status.BAD_REQUEST;
        logger.warn(exception.getMessage());
    } else if (exception instanceof AuthorizationException) {
        // Not enough permissions
        status = Status.UNAUTHORIZED;
        logger.warn(exception.getMessage());
    } else {
        logger.error(exception.getMessage(), exception);
    }
    return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(ErrorEntity.with().message(exception.getMessage()).build()).build();
}
 
Example 8
Source File: ComponentImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public void reloadConnectors(String clientRole) {
    if (!isWorkerServiceAvailable()) {
        throwUnavailableException();
    }
    if (worker().getWorkerConfig().isAuthorizationEnabled()) {
        // Only superuser has permission to do this operation.
        if (!isSuperUser(clientRole)) {
            throw new RestException(Status.UNAUTHORIZED, "This operation requires super-user access");
        }
    }
    try {
        this.worker().getConnectorsManager().reloadConnectors(worker().getWorkerConfig());
    } catch (IOException e) {
        throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
 
Example 9
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 10
Source File: WorkerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public List<WorkerInfo> getCluster(String clientRole) {
    if (!isWorkerServiceAvailable()) {
        throwUnavailableException();
    }

    if (worker().getWorkerConfig().isAuthorizationEnabled() && !isSuperUser(clientRole)) {
        throw new RestException(Status.UNAUTHORIZED, "client is not authorize to perform operation");
    }

    List<WorkerInfo> workers = worker().getMembershipManager().getCurrentMembership();
    return workers;
}
 
Example 11
Source File: WorkerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public List<org.apache.pulsar.common.stats.Metrics> getWorkerMetrics(final String clientRole) {
    if (!isWorkerServiceAvailable()) {
        throwUnavailableException();
    }

    if (worker().getWorkerConfig().isAuthorizationEnabled() && !isSuperUser(clientRole)) {
        log.error("Client [{}] is not authorized to get worker stats", clientRole);
        throw new RestException(Status.UNAUTHORIZED, "client is not authorize to perform operation");
    }
    return worker().getMetricsGenerator().generate();
}
 
Example 12
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
protected static void checkAuthorization(PulsarService pulsarService, TopicName topicName, String role,
        AuthenticationDataSource authenticationData) throws RestException, Exception {
    if (!pulsarService.getConfiguration().isAuthorizationEnabled()) {
        // No enforcing of authorization policies
        return;
    }
    // get zk policy manager
    if (!pulsarService.getBrokerService().getAuthorizationService().canLookup(topicName, role, authenticationData)) {
        log.warn("[{}] Role {} is not allowed to lookup topic", topicName, role);
        throw new RestException(Status.UNAUTHORIZED, "Don't have permission to connect to this namespace");
    }
}
 
Example 13
Source File: AccessDeniedExceptionMapper.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(AccessDeniedException exception) {
    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // if the user was authenticated - forbidden, otherwise unauthorized... the user may be null if the
    // AccessDeniedException was thrown from a /access endpoint that isn't subject to the security
    // filter chain. for instance, one that performs kerberos negotiation
    final Response.Status status;
    if (user == null || user.isAnonymous()) {
        status = Status.UNAUTHORIZED;
    } else {
        status = Status.FORBIDDEN;
    }

    final String identity;
    if (user == null) {
        identity = "<no user found>";
    } else {
        identity = user.toString();
    }

    logger.info(String.format("%s does not have permission to access the requested resource. %s Returning %s response.", identity, exception.getMessage(), status));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(status)
            .entity(String.format("%s Contact the system administrator.", exception.getMessage()))
            .type("text/plain")
            .build();
}
 
Example 14
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void validateTopicOperation(TopicName topicName, TopicOperation operation) {
    if (pulsar().getConfiguration().isAuthenticationEnabled() && pulsar().getBrokerService().isAuthorizationEnabled()) {
        if (!isClientAuthenticated(clientAppId())) {
            throw new RestException(Status.UNAUTHORIZED, "Need to authenticate to perform the request");
        }

        Boolean isAuthorized = pulsar().getBrokerService().getAuthorizationService()
                .allowTopicOperation(topicName, operation, originalPrincipal(), clientAppId(), clientAuthData());

        if (!isAuthorized) {
            throw new RestException(Status.UNAUTHORIZED, String.format("Unauthorized to validateTopicOperation for" +
                    " operation [%s] on topic [%s]", operation.toString(), topicName));
        }
    }
}
 
Example 15
Source File: HsWebServices.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void checkAccess(Job job, HttpServletRequest request) {
  if (!hasAccess(job, request)) {
    throw new WebApplicationException(Status.UNAUTHORIZED);
  }
}
 
Example 16
Source File: HsWebServices.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private void checkAccess(Job job, HttpServletRequest request) {
  if (!hasAccess(job, request)) {
    throw new WebApplicationException(Status.UNAUTHORIZED);
  }
}
 
Example 17
Source File: IssueTypeToHttpStatusMapper.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static Status issueTypeToResponseCode(IssueType.ValueSet value) {
    switch (value) {
    case INFORMATIONAL:
        return Status.OK;
    case FORBIDDEN:
    case SUPPRESSED:
    case SECURITY:
    case THROTTLED:     // Consider HTTP 429?
        return Status.FORBIDDEN;
    case PROCESSING:
    case BUSINESS_RULE: // Consider HTTP 422?
    case CODE_INVALID:  // Consider HTTP 422?
    case EXTENSION:     // Consider HTTP 422?
    case INVALID:       // Consider HTTP 422?
    case INVARIANT:     // Consider HTTP 422?
    case REQUIRED:      // Consider HTTP 422?
    case STRUCTURE:     // Consider HTTP 422?
    case VALUE:         // Consider HTTP 422?
    case TOO_COSTLY:    // Consider HTTP 403?
    case DUPLICATE:     // Consider HTTP 409?
        return Status.BAD_REQUEST;
    case DELETED:
        return Status.GONE;
    case CONFLICT:
        return Status.CONFLICT;
    case MULTIPLE_MATCHES:
        return Status.PRECONDITION_FAILED;
    case EXPIRED:
    case LOGIN:
    case UNKNOWN:
        return Status.UNAUTHORIZED;
    case NOT_FOUND:
    case NOT_SUPPORTED:
        return Status.NOT_FOUND;
    case TOO_LONG:
        return Status.REQUEST_ENTITY_TOO_LARGE;
    case EXCEPTION:
    case LOCK_ERROR:
    case NO_STORE:
    case TIMEOUT:
    case TRANSIENT:
    case INCOMPLETE:
    default:
        return Status.INTERNAL_SERVER_ERROR;
    }
}
 
Example 18
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether the user has Pulsar Super-User access to the system.
 *
 * @throws WebApplicationException
 *             if not authorized
 */
protected void validateSuperUserAccess() {
    if (config().isAuthenticationEnabled()) {
        String appId = clientAppId();
        if(log.isDebugEnabled()) {
            log.debug("[{}] Check super user access: Authenticated: {} -- Role: {}", uri.getRequestUri(),
                    isClientAuthenticated(appId), appId);
        }
        String originalPrincipal = originalPrincipal();
        validateOriginalPrincipal(pulsar.getConfiguration().getProxyRoles(), appId, originalPrincipal);

        if (pulsar.getConfiguration().getProxyRoles().contains(appId)) {

            CompletableFuture<Boolean> proxyAuthorizedFuture;
            CompletableFuture<Boolean> originalPrincipalAuthorizedFuture;

            try {
                proxyAuthorizedFuture = pulsar.getBrokerService()
                        .getAuthorizationService()
                        .isSuperUser(appId, clientAuthData());

                originalPrincipalAuthorizedFuture = pulsar.getBrokerService()
                        .getAuthorizationService()
                        .isSuperUser(originalPrincipal, clientAuthData());

                if (!proxyAuthorizedFuture.get() || !originalPrincipalAuthorizedFuture.get()) {
                    throw new RestException(Status.UNAUTHORIZED,
                            String.format("Proxy not authorized for super-user operation (proxy:%s,original:%s)",
                                          appId, originalPrincipal));
                }
            } catch (InterruptedException | ExecutionException e) {
                throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
            }
            log.debug("Successfully authorized {} (proxied by {}) as super-user",
                      originalPrincipal, appId);
        } else {
            if (config().isAuthorizationEnabled() && !pulsar.getBrokerService()
                    .getAuthorizationService()
                    .isSuperUser(appId, clientAuthData())
                    .join()) {
                throw new RestException(Status.UNAUTHORIZED, "This operation requires super-user access");
            }
            log.debug("Successfully authorized {} as super-user",
                      appId);
        }
    }
}
 
Example 19
Source File: CrnParseExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.UNAUTHORIZED;
}
 
Example 20
Source File: AMWebServices.java    From big-c with Apache License 2.0 2 votes vote down vote up
/**
 * check for job access.
 *
 * @param job
 *          the job that is being accessed
 */
void checkAccess(Job job, HttpServletRequest request) {
  if (!hasAccess(job, request)) {
    throw new WebApplicationException(Status.UNAUTHORIZED);
  }
}