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