Search in sources :

Example 21 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project streamline by hortonworks.

the class NamespaceCatalogResourceTest method testChangeMappingOfStreamingEngineViaSetServicesToClusterInNamespace.

@Test
public void testChangeMappingOfStreamingEngineViaSetServicesToClusterInNamespace() throws Exception {
    Long testNamespaceId = 1L;
    Namespace testNamespace = createTestNamespace(testNamespaceId, TEST_STREAMING_ENGINE, TEST_TIME_SERIES_DB);
    Collection<NamespaceServiceClusterMap> existingMappings = createTestMappingsForExisting(testNamespaceId);
    setupExpectationForSimulatingTopologyIsRunning(testNamespaceId, testNamespace, existingMappings);
    List<NamespaceServiceClusterMap> mappingsToApply = existingMappings.stream().filter(m -> !m.getServiceName().equals(TEST_STREAMING_ENGINE)).collect(toList());
    // change the mapping of streaming engine to cluster id 2
    mappingsToApply.add(new NamespaceServiceClusterMap(testNamespaceId, TEST_STREAMING_ENGINE, 2L));
    try {
        namespaceCatalogResource.setServicesToClusterInNamespace(testNamespaceId, mappingsToApply, securityContext);
        Assert.fail("Should throw BadRequestException");
    } catch (BadRequestException e) {
    // passed
    }
    new Verifications() {

        {
            // request fails before removing existing mappings
            environmentService.removeServiceClusterMapping(testNamespaceId, anyString, anyLong);
            times = 0;
        }
    };
}
Also used : Topology(com.hortonworks.streamline.streams.catalog.Topology) NamespaceServiceClusterMap(com.hortonworks.streamline.streams.cluster.catalog.NamespaceServiceClusterMap) Expectations(mockit.Expectations) BadRequestException(com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException) RunWith(org.junit.runner.RunWith) SecurityContext(javax.ws.rs.core.SecurityContext) ArrayList(java.util.ArrayList) EnvironmentService(com.hortonworks.streamline.streams.cluster.service.EnvironmentService) TopologyNotAliveException(com.hortonworks.streamline.streams.exception.TopologyNotAliveException) Lists(com.google.common.collect.Lists) JMockit(mockit.integration.junit4.JMockit) StreamlineAuthorizer(com.hortonworks.streamline.streams.security.StreamlineAuthorizer) Namespace(com.hortonworks.streamline.streams.cluster.catalog.Namespace) Tested(mockit.Tested) TopologyActionsService(com.hortonworks.streamline.streams.actions.topology.service.TopologyActionsService) Collection(java.util.Collection) Test(org.junit.Test) IOException(java.io.IOException) NoopAuthorizer(com.hortonworks.streamline.streams.security.impl.NoopAuthorizer) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) StreamCatalogService(com.hortonworks.streamline.streams.catalog.service.StreamCatalogService) Injectable(mockit.Injectable) Assert(org.junit.Assert) Verifications(mockit.Verifications) BadRequestException(com.hortonworks.streamline.common.exception.service.exception.request.BadRequestException) Verifications(mockit.Verifications) NamespaceServiceClusterMap(com.hortonworks.streamline.streams.cluster.catalog.NamespaceServiceClusterMap) Namespace(com.hortonworks.streamline.streams.cluster.catalog.Namespace) Test(org.junit.Test)

Example 22 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project divide by HiddenStage.

the class ResponseFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    SecurityContext context = requestContext.getSecurityContext();
    if (context != null && context instanceof UserContext) {
        UserContext userContext = (UserContext) context;
        Credentials user = userContext.getUser();
        if (user != null && user.getAuthToken() != null) {
            responseContext.getHeaders().add("Authorization", user.getAuthToken());
        }
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) Credentials(io.divide.shared.transitory.Credentials)

Example 23 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project dropwizard by dropwizard.

the class AuthFilter method authenticate.

/**
 * Authenticates a request with user credentials and setup the security context.
 *
 * @param requestContext the context of the request
 * @param credentials    the user credentials
 * @param scheme         the authentication scheme; one of {@code BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH}.
 *                       See {@link SecurityContext}
 * @return {@code true}, if the request is authenticated, otherwise {@code false}
 */
protected boolean authenticate(ContainerRequestContext requestContext, @Nullable C credentials, String scheme) {
    try {
        if (credentials == null) {
            return false;
        }
        final Optional<P> principal = authenticator.authenticate(credentials);
        if (!principal.isPresent()) {
            return false;
        }
        final P prince = principal.get();
        final SecurityContext securityContext = requestContext.getSecurityContext();
        final boolean secure = securityContext != null && securityContext.isSecure();
        requestContext.setSecurityContext(new SecurityContext() {

            @Override
            public Principal getUserPrincipal() {
                return prince;
            }

            @Override
            public boolean isUserInRole(String role) {
                return authorizer.authorize(prince, role, requestContext);
            }

            @Override
            public boolean isSecure() {
                return secure;
            }

            @Override
            public String getAuthenticationScheme() {
                return scheme;
            }
        });
        return true;
    } catch (AuthenticationException e) {
        logger.warn("Error authenticating credentials", e);
        throw new InternalServerErrorException();
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Principal(java.security.Principal)

Example 24 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project indy by Commonjava.

the class PathMappedResource method get.

@ApiOperation("Get specified path.")
@ApiResponse(code = 200, message = "Operation finished.")
@GET
@Path(CONCRETE_CONTENT_PATH)
public Response get(@PathParam("packageType") final String packageType, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @ApiParam(required = true) @PathParam("name") final String name, @PathParam("path") final String path, @Context final HttpServletRequest request, @Context final SecurityContext securityContext) {
    try {
        InputStream inputStream = controller.get(packageType, type, name, path);
        Response.ResponseBuilder builder = Response.ok((StreamingOutput) outputStream -> IOUtils.copy(inputStream, outputStream));
        return builder.header(ApplicationHeader.content_type.key(), mimeTyper.getContentType(path)).build();
    } catch (Exception e) {
        logger.warn("Get pathmap content failed, message: " + e.getMessage(), e);
        if (e.getMessage() != null && e.getMessage().contains("not exist")) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        responseHelper.throwError(e);
    }
    return null;
}
Also used : Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) PathParam(javax.ws.rs.PathParam) REST(org.commonjava.indy.bind.jaxrs.util.REST) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) PathMappedListResult(org.commonjava.indy.pathmapped.model.PathMappedListResult) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) ApiParam(io.swagger.annotations.ApiParam) ApplicationContent.application_json(org.commonjava.indy.util.ApplicationContent.application_json) ROOT_DIR(org.commonjava.storage.pathmapped.util.PathMapUtils.ROOT_DIR) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) HttpServletRequest(javax.servlet.http.HttpServletRequest) QueryParam(javax.ws.rs.QueryParam) SecurityManager(org.commonjava.indy.bind.jaxrs.SecurityManager) Api(io.swagger.annotations.Api) ApplicationHeader(org.commonjava.indy.util.ApplicationHeader) DELETE(javax.ws.rs.DELETE) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) ResponseHelper(org.commonjava.indy.bind.jaxrs.util.ResponseHelper) PathMappedDeleteResult(org.commonjava.indy.pathmapped.model.PathMappedDeleteResult) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IndyResources(org.commonjava.indy.bind.jaxrs.IndyResources) StreamingOutput(javax.ws.rs.core.StreamingOutput) MimeTyper(org.commonjava.indy.util.MimeTyper) IOUtils(org.apache.commons.io.IOUtils) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) PathMappedController(org.commonjava.indy.pathmapped.common.PathMappedController) InputStream(java.io.InputStream) InputStream(java.io.InputStream) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponse(io.swagger.annotations.ApiResponse)

Example 25 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project tomee by apache.

the class MPJWTSecurityAnnotationsInterceptor method filter.

@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    if (permitAll.contains(resourceInfo.getResourceMethod())) {
        return;
    }
    if (denyAll.contains(resourceInfo.getResourceMethod())) {
        forbidden(requestContext);
        return;
    }
    final Set<String> roles = rolesAllowed.get(resourceInfo.getResourceMethod());
    if (roles != null && !roles.isEmpty()) {
        final SecurityContext securityContext = requestContext.getSecurityContext();
        boolean hasAtLeasOneValidRole = false;
        for (String role : roles) {
            if (securityContext.isUserInRole(role)) {
                hasAtLeasOneValidRole = true;
                break;
            }
        }
        if (!hasAtLeasOneValidRole) {
            forbidden(requestContext);
        }
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext)

Aggregations

SecurityContext (javax.ws.rs.core.SecurityContext)77 Response (javax.ws.rs.core.Response)30 Context (javax.ws.rs.core.Context)18 Test (org.junit.Test)18 List (java.util.List)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