Search in sources :

Example 1 with ForbiddenException

use of javax.ws.rs.ForbiddenException in project jersey by jersey.

the class JerseyInvocation method convertToException.

private ProcessingException convertToException(final Response response) {
    try {
        // Buffer and close entity input stream (if any) to prevent
        // leaking connections (see JERSEY-2157).
        response.bufferEntity();
        final WebApplicationException webAppException;
        final int statusCode = response.getStatus();
        final Response.Status status = Response.Status.fromStatusCode(statusCode);
        if (status == null) {
            final Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
            webAppException = createExceptionForFamily(response, statusFamily);
        } else {
            switch(status) {
                case BAD_REQUEST:
                    webAppException = new BadRequestException(response);
                    break;
                case UNAUTHORIZED:
                    webAppException = new NotAuthorizedException(response);
                    break;
                case FORBIDDEN:
                    webAppException = new ForbiddenException(response);
                    break;
                case NOT_FOUND:
                    webAppException = new NotFoundException(response);
                    break;
                case METHOD_NOT_ALLOWED:
                    webAppException = new NotAllowedException(response);
                    break;
                case NOT_ACCEPTABLE:
                    webAppException = new NotAcceptableException(response);
                    break;
                case UNSUPPORTED_MEDIA_TYPE:
                    webAppException = new NotSupportedException(response);
                    break;
                case INTERNAL_SERVER_ERROR:
                    webAppException = new InternalServerErrorException(response);
                    break;
                case SERVICE_UNAVAILABLE:
                    webAppException = new ServiceUnavailableException(response);
                    break;
                default:
                    final Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
                    webAppException = createExceptionForFamily(response, statusFamily);
            }
        }
        return new ResponseProcessingException(response, webAppException);
    } catch (final Throwable t) {
        return new ResponseProcessingException(response, LocalizationMessages.RESPONSE_TO_EXCEPTION_CONVERSION_FAILED(), t);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) WebApplicationException(javax.ws.rs.WebApplicationException) NotAllowedException(javax.ws.rs.NotAllowedException) NotFoundException(javax.ws.rs.NotFoundException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Response(javax.ws.rs.core.Response) NotAcceptableException(javax.ws.rs.NotAcceptableException) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) NotSupportedException(javax.ws.rs.NotSupportedException)

Example 2 with ForbiddenException

use of javax.ws.rs.ForbiddenException in project keywhiz by square.

the class AutomationClientAuthFactory method provide.

public AutomationClient provide(ContainerRequest request) {
    Optional<String> possibleClientName = ClientAuthFactory.getClientName(request);
    if (!possibleClientName.isPresent()) {
        throw new NotAuthorizedException("Not authorized as a AutomationClient");
    }
    String clientName = possibleClientName.get();
    try {
        return authenticator.authenticate(clientName).orElseThrow(() -> new ForbiddenException(format("ClientCert name %s not authorized as a AutomationClient", clientName)));
    } catch (AuthenticationException e) {
        throw Throwables.propagate(e);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) AuthenticationException(io.dropwizard.auth.AuthenticationException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException)

Example 3 with ForbiddenException

use of javax.ws.rs.ForbiddenException in project graylog2-server by Graylog2.

the class ShiroAuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (securityContext instanceof ShiroSecurityContext) {
        final ShiroSecurityContext context = (ShiroSecurityContext) securityContext;
        final String userName = RestTools.getUserNameFromRequest(requestContext);
        final ContextAwarePermissionAnnotationHandler annotationHandler = new ContextAwarePermissionAnnotationHandler(context);
        try {
            LOG.debug("Checking authorization for user [{}], needs permissions: {}", userName, annotation.value());
            annotationHandler.assertAuthorized(annotation);
        } catch (AuthorizationException e) {
            final String msg = String.format(Locale.US, "User [%s] not authorized. (%s %s)", userName, requestContext.getMethod(), requestContext.getUriInfo().getPath());
            LOG.info(msg);
            throw new ForbiddenException(msg);
        }
    } else {
        throw new ForbiddenException();
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) AuthorizationException(org.apache.shiro.authz.AuthorizationException) SecurityContext(javax.ws.rs.core.SecurityContext)

Example 4 with ForbiddenException

use of javax.ws.rs.ForbiddenException in project keywhiz by square.

the class LdapAuthenticator method authenticate.

@Override
public Optional<User> authenticate(BasicCredentials credentials) {
    User user = null;
    try {
        String username = credentials.getUsername();
        if (!User.isSanitizedUsername(username)) {
            logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN);
            return Optional.empty();
        }
        String userDN = dnFromUsername(username);
        String password = credentials.getPassword();
        // Must have password for current config
        if (Strings.isNullOrEmpty(password)) {
            logger.info("No password for user provided");
            return Optional.empty();
        }
        LDAPConnection authenticatedConnection = connectionFactory.getLDAPConnection(userDN, password);
        authenticatedConnection.close();
        Set<String> requiredRoles = config.getRequiredRoles();
        if (!requiredRoles.isEmpty()) {
            Set<String> roles = rolesFromDN(userDN);
            boolean accessAllowed = false;
            for (String requiredRole : requiredRoles) {
                if (roles.contains(requiredRole)) {
                    accessAllowed = true;
                }
            }
            if (!accessAllowed) {
                logger.warn("User {} not in one of required LDAP roles: [{}].", username, requiredRoles);
                throw new ForbiddenException();
            }
        }
        user = User.named(username);
    } catch (LDAPException le) {
        // The INVALID_CREDENTIALS case is handled by returning an absent optional from this function
        if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
            logger.error("Error connecting to LDAP", le);
            throw Throwables.propagate(le);
        }
    } catch (GeneralSecurityException gse) {
        logger.error("TLS error connecting to LDAP", gse);
        throw Throwables.propagate(gse);
    }
    return Optional.ofNullable(user);
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) User(keywhiz.auth.User) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection)

Example 5 with ForbiddenException

use of javax.ws.rs.ForbiddenException in project keywhiz by square.

the class SecretDeliveryResource method getSecret.

/**
   * Retrieve Secret by name
   *
   * @excludeParams client
   * @param secretName the name of the Secret to retrieve
   *
   * @description Returns a single Secret if found
   * @responseMessage 200 Found and retrieved Secret with given name
   * @responseMessage 403 Secret is not assigned to Client
   * @responseMessage 404 Secret with given name not found
   * @responseMessage 500 Secret response could not be generated for given Secret
   */
@Timed
@ExceptionMetered
@GET
public SecretDeliveryResponse getSecret(@NotEmpty @PathParam("secretName") String secretName, @Auth Client client) {
    Optional<SanitizedSecret> sanitizedSecret = aclDAO.getSanitizedSecretFor(client, secretName);
    Optional<Secret> secret = secretController.getSecretByName(secretName);
    if (!sanitizedSecret.isPresent()) {
        boolean clientExists = clientDAO.getClient(client.getName()).isPresent();
        boolean secretExists = secret.isPresent();
        if (clientExists && secretExists) {
            throw new ForbiddenException(format("Access denied: %s at '%s' by '%s'", client.getName(), "/secret/" + secretName, client));
        } else {
            if (clientExists) {
                logger.info("Client {} requested unknown secret {}", client.getName(), secretName);
            }
            throw new NotFoundException();
        }
    }
    logger.info("Client {} granted access to {}.", client.getName(), secretName);
    try {
        return SecretDeliveryResponse.fromSecret(secret.get());
    } catch (IllegalArgumentException e) {
        logger.error(format("Failed creating response for secret %s", secretName), e);
        throw new InternalServerErrorException();
    }
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) ForbiddenException(javax.ws.rs.ForbiddenException) NotFoundException(javax.ws.rs.NotFoundException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Aggregations

ForbiddenException (javax.ws.rs.ForbiddenException)10 Timed (com.codahale.metrics.annotation.Timed)5 ApiOperation (io.swagger.annotations.ApiOperation)5 AuditEvent (org.graylog2.audit.jersey.AuditEvent)5 BadRequestException (javax.ws.rs.BadRequestException)4 NotFoundException (javax.ws.rs.NotFoundException)4 Path (javax.ws.rs.Path)4 ApiResponses (io.swagger.annotations.ApiResponses)3 Produces (javax.ws.rs.Produces)3 SystemJob (org.graylog2.system.jobs.SystemJob)3 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)2 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)2 POST (javax.ws.rs.POST)2 PUT (javax.ws.rs.PUT)2 SystemJobConcurrencyException (org.graylog2.system.jobs.SystemJobConcurrencyException)2 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)1 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)1 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 AuthenticationException (io.dropwizard.auth.AuthenticationException)1 GeneralSecurityException (java.security.GeneralSecurityException)1