Search in sources :

Example 1 with NotAuthorizedException

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

the class OAuth1AuthorizationFlowImpl method finish.

public AccessToken finish(final String verifier) {
    parameters.setVerifier(verifier);
    final Response response = addProperties(client.target(accessTokenUri).request()).post(null);
    // accessToken request failed
    if (response.getStatus() >= 400) {
        throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_ACCESS_TOKEN(response.getStatus()));
    }
    final Form form = response.readEntity(Form.class);
    final String accessToken = form.asMap().getFirst(OAuth1Parameters.TOKEN);
    final String accessTokenSecret = form.asMap().getFirst(OAuth1Parameters.TOKEN_SECRET);
    if (accessToken == null) {
        throw new NotAuthorizedException(LocalizationMessages.ERROR_REQUEST_ACCESS_TOKEN_NULL());
    }
    parameters.token(accessToken);
    secrets.tokenSecret(accessTokenSecret);
    final AccessToken resultToken = new AccessToken(parameters.getToken(), secrets.getTokenSecret());
    this.accessToken = resultToken;
    return resultToken;
}
Also used : Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) NotAuthorizedException(javax.ws.rs.NotAuthorizedException)

Example 2 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 SessionResponse newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Username and credentials", required = true) @Valid @NotNull SessionCreateRequest 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;
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    // pretend that we had session id before
    Serializable id = null;
    if (sessionId != null && !sessionId.isEmpty()) {
        id = sessionId;
    }
    final String remoteAddrFromRequest = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
    ThreadContext.bind(subject);
    final Session s = subject.getSession();
    try {
        subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
        final User user = userService.load(createRequest.username());
        if (user != null) {
            long timeoutInMillis = user.getSessionTimeoutMs();
            s.setTimeout(timeoutInMillis);
        } else {
            // set a sane default. really we should be able to load the user from above.
            s.setTimeout(TimeUnit.HOURS.toMillis(8));
        }
        s.touch();
        // save subject in session, otherwise we can't get the username back in subsequent requests.
        ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
    } catch (AuthenticationException e) {
        LOG.info("Invalid username or password for user \"{}\"", createRequest.username());
    } catch (UnknownSessionException e) {
        subject.logout();
    }
    if (subject.isAuthenticated()) {
        id = s.getId();
        final Map<String, Object> auditEventContext = ImmutableMap.of("session_id", id, "remote_address", remoteAddrFromRequest);
        auditEventSender.success(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        // TODO is the validUntil attribute even used by anyone yet?
        return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(), id.toString());
    } else {
        final Map<String, Object> auditEventContext = ImmutableMap.of("remote_address", remoteAddrFromRequest);
        auditEventSender.failure(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
        throw new NotAuthorizedException("Invalid username or password", "Basic realm=\"Graylog Server session\"");
    }
}
Also used : Serializable(java.io.Serializable) User(org.graylog2.plugin.database.users.User) AuthenticationException(org.apache.shiro.authc.AuthenticationException) UnknownSessionException(org.apache.shiro.session.UnknownSessionException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) DateTime(org.joda.time.DateTime) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) 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)

Example 3 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException 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 4 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException 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 5 with NotAuthorizedException

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

the class ClientAuthFactory method provide.

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

Aggregations

NotAuthorizedException (javax.ws.rs.NotAuthorizedException)21 ForbiddenException (javax.ws.rs.ForbiddenException)5 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)5 Response (javax.ws.rs.core.Response)4 SecurityContext (javax.ws.rs.core.SecurityContext)4 ApiOperation (io.swagger.annotations.ApiOperation)3 BadRequestException (javax.ws.rs.BadRequestException)3 NotFoundException (javax.ws.rs.NotFoundException)3 POST (javax.ws.rs.POST)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 ProcessingException (javax.ws.rs.ProcessingException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2