use of javax.ws.rs.NotAuthorizedException in project minijax by minijax.
the class MinijaxApplication method checkSecurity.
private void checkSecurity(final MinijaxRequestContext context) {
final Annotation a = context.getResourceMethod().getSecurityAnnotation();
if (a == null) {
return;
}
final Class<?> c = a.annotationType();
if (c == PermitAll.class) {
return;
}
if (c == DenyAll.class) {
throw new ForbiddenException();
}
if (c == RolesAllowed.class) {
final SecurityContext security = context.getSecurityContext();
if (security == null || security.getUserPrincipal() == null) {
throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).build());
}
boolean found = false;
for (final String role : ((RolesAllowed) a).value()) {
if (security.isUserInRole(role)) {
found = true;
break;
}
}
if (!found) {
throw new ForbiddenException();
}
}
}
use of javax.ws.rs.NotAuthorizedException in project atlasdb by palantir.
the class RsErrorDecoder method decode.
@Override
public RuntimeException decode(String methodKey, feign.Response feignResponse) {
try {
Response response = convertResponseToRs(feignResponse);
int statusCode = response.getStatus();
Response.Status status = Response.Status.fromStatusCode(statusCode);
if (status == null) {
Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
return createExceptionForFamily(response, statusFamily);
} else {
switch(status) {
case BAD_REQUEST:
return new BadRequestException(response);
case UNAUTHORIZED:
return new NotAuthorizedException(response);
case FORBIDDEN:
return new ForbiddenException(response);
case NOT_FOUND:
return new NotFoundException(response);
case METHOD_NOT_ALLOWED:
return new NotAllowedException(response);
case NOT_ACCEPTABLE:
return new NotAcceptableException(response);
case UNSUPPORTED_MEDIA_TYPE:
return new NotSupportedException(response);
case INTERNAL_SERVER_ERROR:
return new InternalServerErrorException(response);
case SERVICE_UNAVAILABLE:
return new ServiceUnavailableException(response);
default:
Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
return createExceptionForFamily(response, statusFamily);
}
}
} catch (Throwable t) {
return new RuntimeException("Failed to convert response to exception", t);
}
}
use of javax.ws.rs.NotAuthorizedException in project syncope by apache.
the class SCIMExceptionMapper method toResponse.
@Override
public Response toResponse(final Exception ex) {
LOG.error("Exception thrown", ex);
ResponseBuilder builder;
if (ex instanceof AccessDeniedException || ex instanceof ForbiddenException || ex instanceof NotAuthorizedException) {
// leaves the default exception processing
builder = null;
} else if (ex instanceof NotFoundException) {
return Response.status(Response.Status.NOT_FOUND).entity(new SCIMError(null, Response.Status.NOT_FOUND.getStatusCode(), ExceptionUtils.getRootCauseMessage(ex))).build();
} else if (ex instanceof SyncopeClientException) {
SyncopeClientException sce = (SyncopeClientException) ex;
builder = builder(sce.getType(), ExceptionUtils.getRootCauseMessage(ex));
} else if (ex instanceof DelegatedAdministrationException || ExceptionUtils.getRootCause(ex) instanceof DelegatedAdministrationException) {
builder = builder(ClientExceptionType.DelegatedAdministration, ExceptionUtils.getRootCauseMessage(ex));
} else if (ENTITYEXISTS_EXCLASS.isAssignableFrom(ex.getClass()) || ex instanceof DuplicateException || PERSISTENCE_EXCLASS.isAssignableFrom(ex.getClass()) && ENTITYEXISTS_EXCLASS.isAssignableFrom(ex.getCause().getClass())) {
builder = builder(ClientExceptionType.EntityExists, ExceptionUtils.getRootCauseMessage(ex));
} else if (ex instanceof DataIntegrityViolationException || JPASYSTEM_EXCLASS.isAssignableFrom(ex.getClass())) {
builder = builder(ClientExceptionType.DataIntegrityViolation, ExceptionUtils.getRootCauseMessage(ex));
} else if (CONNECTOR_EXCLASS.isAssignableFrom(ex.getClass())) {
builder = builder(ClientExceptionType.ConnectorException, ExceptionUtils.getRootCauseMessage(ex));
} else {
builder = processInvalidEntityExceptions(ex);
if (builder == null) {
builder = processBadRequestExceptions(ex);
}
// process JAX-RS validation errors
if (builder == null && ex instanceof ValidationException) {
builder = builder(ClientExceptionType.RESTValidation, ExceptionUtils.getRootCauseMessage(ex));
}
// ...or just report as InternalServerError
if (builder == null) {
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionUtils.getRootCauseMessage(ex));
}
}
return builder == null ? null : builder.build();
}
use of javax.ws.rs.NotAuthorizedException in project graylog2-server by Graylog2.
the class SessionsResource method validateSession.
@GET
@ApiOperation(value = "Validate an existing session", notes = "Checks the session with the given ID: returns http status 204 (No Content) if session is valid.", code = 204)
public SessionValidationResponse validateSession(@Context ContainerRequestContext requestContext) {
try {
this.authenticationFilter.filter(requestContext);
} catch (NotAuthorizedException | LockedAccountException | IOException e) {
return SessionValidationResponse.invalid();
}
final Subject subject = getSubject();
if (!subject.isAuthenticated()) {
return SessionValidationResponse.invalid();
}
// session information from the response to perform subsequent requests to the backend using this session.
if (subject.getSession(false) == null && ShiroSecurityContext.isSessionCreationRequested()) {
final Session session = subject.getSession();
final String userId = subject.getPrincipal().toString();
final User user = userService.loadById(userId);
if (user == null) {
throw new InternalServerErrorException("Unable to load user with ID <" + userId + ">.");
}
session.setAttribute("username", user.getName());
final HTTPHeaderAuthConfig httpHeaderConfig = loadHTTPHeaderConfig();
final Optional<String> usernameHeader = ShiroRequestHeadersBinder.getHeaderFromThreadContext(httpHeaderConfig.usernameHeader());
if (httpHeaderConfig.enabled() && usernameHeader.isPresent()) {
session.setAttribute(HTTPHeaderAuthenticationRealm.SESSION_AUTH_HEADER, usernameHeader.get());
}
LOG.debug("Create session for <{}>", user.getName());
session.touch();
// save subject in session, otherwise we can't get the username back in subsequent requests.
((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
return SessionValidationResponse.validWithNewSession(String.valueOf(session.getId()), String.valueOf(user.getName()));
}
return SessionValidationResponse.valid();
}
use of javax.ws.rs.NotAuthorizedException in project graylog2-server by Graylog2.
the class SessionsResource method newSession.
@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or " + "reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public JsonNode newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Credentials. The default " + "implementation requires presence of two properties: 'username' and " + "'password'. However a plugin may customize which kind of credentials " + "are accepted and therefore expect different properties.", required = true) @NotNull JsonNode createRequest) {
final SecurityContext securityContext = requestContext.getSecurityContext();
if (!(securityContext instanceof ShiroSecurityContext)) {
throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
}
final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
final ActorAwareAuthenticationToken authToken;
try {
authToken = tokenFactory.forRequestBody(createRequest);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
// we treat the BASIC auth username as the sessionid
final String sessionId = shiroSecurityContext.getUsername();
final String host = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
try {
Optional<Session> session = sessionCreator.create(sessionId, host, authToken);
if (session.isPresent()) {
return sessionResponseFactory.forSession(session.get());
} else {
throw new NotAuthorizedException("Invalid credentials.", "Basic realm=\"Graylog Server session\"");
}
} catch (AuthenticationServiceUnavailableException e) {
throw new ServiceUnavailableException("Authentication service unavailable");
}
}
Aggregations