Search in sources :

Example 11 with NotAuthorizedException

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();
        }
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) RolesAllowed(javax.annotation.security.RolesAllowed) SecurityContext(javax.ws.rs.core.SecurityContext) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Annotation(java.lang.annotation.Annotation)

Example 12 with NotAuthorizedException

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);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) 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) NotSupportedException(javax.ws.rs.NotSupportedException)

Example 13 with NotAuthorizedException

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();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ForbiddenException(javax.ws.rs.ForbiddenException) ValidationException(javax.validation.ValidationException) ParsingValidationException(org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException) DuplicateException(org.apache.syncope.core.persistence.api.dao.DuplicateException) SCIMError(org.apache.syncope.ext.scimv2.api.data.SCIMError) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) DelegatedAdministrationException(org.apache.syncope.core.spring.security.DelegatedAdministrationException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 14 with NotAuthorizedException

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();
}
Also used : HTTPHeaderAuthConfig(org.graylog2.security.headerauth.HTTPHeaderAuthConfig) User(org.graylog2.plugin.database.users.User) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) IOException(java.io.IOException) LockedAccountException(org.apache.shiro.authc.LockedAccountException) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 15 with NotAuthorizedException

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");
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) ActorAwareAuthenticationToken(org.graylog2.shared.security.ActorAwareAuthenticationToken) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Aggregations

NotAuthorizedException (javax.ws.rs.NotAuthorizedException)28 ForbiddenException (javax.ws.rs.ForbiddenException)5 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)5 POST (javax.ws.rs.POST)5 Response (javax.ws.rs.core.Response)5 NotFoundException (javax.ws.rs.NotFoundException)4 SecurityContext (javax.ws.rs.core.SecurityContext)4 ApiOperation (io.swagger.annotations.ApiOperation)3 BadRequestException (javax.ws.rs.BadRequestException)3 Produces (javax.ws.rs.Produces)3 ServiceUnavailableException (javax.ws.rs.ServiceUnavailableException)3 Session (org.apache.shiro.session.Session)3 Subject (org.apache.shiro.subject.Subject)3 AuthenticationException (io.dropwizard.auth.AuthenticationException)2 IOException (java.io.IOException)2 URI (java.net.URI)2 NotAcceptableException (javax.ws.rs.NotAcceptableException)2 NotAllowedException (javax.ws.rs.NotAllowedException)2 NotSupportedException (javax.ws.rs.NotSupportedException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2