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);
}
}
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);
}
}
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();
}
}
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);
}
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();
}
}
Aggregations