Search in sources :

Example 1 with SecurityContext

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

Example 2 with SecurityContext

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));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ByteArrayInputStream(java.io.ByteArrayInputStream) SecurityContext(javax.ws.rs.core.SecurityContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate) Principal(java.security.Principal) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException)

Example 3 with SecurityContext

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;
        }
    };
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) SimpleSecurityContext(org.everrest.core.tools.SimpleSecurityContext) Subject(org.eclipse.che.commons.subject.Subject) SimplePrincipal(org.everrest.core.tools.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.everrest.core.tools.SimplePrincipal)

Example 4 with SecurityContext

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\"");
    }
}
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 5 with SecurityContext

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);
    }
}
Also used : ROLE_MOBILE(org.opennms.web.api.Authentication.ROLE_MOBILE) ROLE_READONLY(org.opennms.web.api.Authentication.ROLE_READONLY) Arrays(java.util.Arrays) ROLE_DELEGATE(org.opennms.web.api.Authentication.ROLE_DELEGATE) Assert.assertNotNull(org.junit.Assert.assertNotNull) SecurityContext(javax.ws.rs.core.SecurityContext) ROLE_ADMIN(org.opennms.web.api.Authentication.ROLE_ADMIN) Set(java.util.Set) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Matchers.anyString(org.mockito.Matchers.anyString) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) Assert.assertNull(org.junit.Assert.assertNull) WebApplicationException(javax.ws.rs.WebApplicationException) RETURNS_DEEP_STUBS(org.mockito.Mockito.RETURNS_DEEP_STUBS) ROLE_USER(org.opennms.web.api.Authentication.ROLE_USER) ROLE_REST(org.opennms.web.api.Authentication.ROLE_REST) Mockito.mock(org.mockito.Mockito.mock) WebApplicationException(javax.ws.rs.WebApplicationException) SecurityContext(javax.ws.rs.core.SecurityContext) Matchers.anyString(org.mockito.Matchers.anyString) HashSet(java.util.HashSet)

Aggregations

SecurityContext (javax.ws.rs.core.SecurityContext)74 Response (javax.ws.rs.core.Response)30 Test (org.junit.Test)18 List (java.util.List)17 Context (javax.ws.rs.core.Context)17 Principal (java.security.Principal)16 LoggerFactory (org.slf4j.LoggerFactory)16 Logger (org.slf4j.Logger)12 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 Path (javax.ws.rs.Path)11 IOException (java.io.IOException)10 POST (javax.ws.rs.POST)8 LocalPasswordHandler (com.emc.storageos.systemservices.impl.util.LocalPasswordHandler)6 GET (javax.ws.rs.GET)6 PathParam (javax.ws.rs.PathParam)6 Produces (javax.ws.rs.Produces)6 MediaType (javax.ws.rs.core.MediaType)6 Status (javax.ws.rs.core.Response.Status)6 UriInfo (javax.ws.rs.core.UriInfo)6