use of javax.ws.rs.core.SecurityContext in project jersey by jersey.
the class SecurityHelperTest method testFilteringScopesWithContext.
@Test
public void testFilteringScopesWithContext() throws Exception {
final SecurityContext context = new TestSecurityContext();
Annotation[] annotations;
Set<String> expected;
// Empty annotations.
annotations = new Annotation[0];
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(Collections.<String>emptySet()));
// Not security annotations.
annotations = new Annotation[] { CustomAnnotationLiteral.INSTANCE, CustomAnnotationLiteral.INSTANCE };
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(Collections.<String>emptySet()));
// Mixed.
annotations = new Annotation[] { CustomAnnotationLiteral.INSTANCE, SecurityAnnotations.rolesAllowed("manager"), CustomAnnotationLiteral.INSTANCE };
expected = Collections.singleton(RolesAllowed.class.getName() + "_manager");
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(expected));
// Multiple.
annotations = new Annotation[] { SecurityAnnotations.rolesAllowed("client", "user") };
expected = Collections.singleton(RolesAllowed.class.getName() + "_user");
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(expected));
// PermitAll weirdo.
annotations = new Annotation[] { SecurityAnnotations.permitAll() };
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(FilteringHelper.getDefaultFilteringScope()));
// DenyAll weirdo.
annotations = new Annotation[] { SecurityAnnotations.denyAll() };
assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(null));
}
use of javax.ws.rs.core.SecurityContext in project jersey by jersey.
the class InMemoryConnector method apply.
/**
* {@inheritDoc}
* <p/>
* Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
* instance).
*
* @param clientRequest client side request to be invoked.
*/
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
if (clientRequest.getEntity() != null) {
clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
}
return clientOutput;
}
});
clientRequest.enableBuffering();
try {
clientRequest.writeEntity();
} catch (IOException e) {
final String msg = "Error while writing entity to the output stream.";
LOGGER.log(Level.SEVERE, msg, e);
throw new ProcessingException(msg, e);
}
}
containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
containerRequest.setWriter(inMemoryResponseWriter);
containerRequest.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String getAuthenticationScheme() {
return null;
}
});
appHandler.handle(containerRequest);
return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
use of javax.ws.rs.core.SecurityContext in project che by eclipse.
the class ServerContainerInitializeListener method createSecurityContext.
protected SecurityContext createSecurityContext(final HandshakeRequest req) {
//todo: get somehow from request
final boolean isSecure = false;
final String authType = "BASIC";
final Subject subject = EnvironmentContext.getCurrent().getSubject();
final Principal principal = new SimplePrincipal(subject.getUserName());
return new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return principal;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public boolean isSecure() {
return isSecure;
}
@Override
public String getAuthenticationScheme() {
return authType;
}
};
}
use of javax.ws.rs.core.SecurityContext 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.core.SecurityContext in project opennms by OpenNMS.
the class SecurityHelperTest method assertUserEditPrivileges.
private void assertUserEditPrivileges(boolean isAllowed, String ackUser, String... roles) {
final Set<String> userRoles = new HashSet<>(Arrays.asList(roles));
SecurityContext securityContext = mock(SecurityContext.class, RETURNS_DEEP_STUBS);
when(securityContext.getUserPrincipal().getName()).thenReturn(USER);
when(securityContext.isUserInRole(anyString())).thenAnswer((Answer) invocation -> {
final String role = invocation.getArgumentAt(0, String.class);
return userRoles.contains(role);
});
WebApplicationException ex = null;
try {
SecurityHelper.assertUserEditCredentials(securityContext, ackUser);
} catch (WebApplicationException e) {
ex = e;
}
if (isAllowed) {
assertNull("Should be allowed, but got: " + ex, ex);
} else {
assertNotNull("Should not be allowed, but passed.", ex);
}
}
Aggregations