Search in sources :

Example 51 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project crnk-framework by crnk-project.

the class JaxrsParameterProviderTest method onSecurityContextParameterShouldReturnThisInstance.

@Test
public void onSecurityContextParameterShouldReturnThisInstance() throws Exception {
    // GIVEN
    SecurityContext securityContext = mock(SecurityContext.class);
    when(requestContext.getSecurityContext()).thenReturn(securityContext);
    // WHEN
    Object result = sut.provide(testMethod, 1);
    // THEN
    verify(requestContext).getSecurityContext();
    assertThat(result).isEqualTo(securityContext);
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) Test(org.junit.Test)

Example 52 with SecurityContext

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

the class SecurityRequestFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (requestContext.getMethod().equals("OPTIONS")) {
        return;
    }
    SecurityContext securityContext = null;
    try {
        String authHeader = requestContext.getHeaderString(AUTHORIZATION_HEADER);
        if (authHeader != null) {
            try {
                String[] auth = decodeBasicAuth(authHeader);
                User user = Context.getPermissionsManager().login(auth[0], auth[1]);
                if (user != null) {
                    Context.getStatisticsManager().registerRequest(user.getId());
                    securityContext = new UserSecurityContext(new UserPrincipal(user.getId()));
                }
            } catch (SQLException e) {
                throw new WebApplicationException(e);
            }
        } else if (request.getSession() != null) {
            Long userId = (Long) request.getSession().getAttribute(SessionResource.USER_ID_KEY);
            if (userId != null) {
                Context.getPermissionsManager().checkUserEnabled(userId);
                Context.getStatisticsManager().registerRequest(userId);
                securityContext = new UserSecurityContext(new UserPrincipal(userId));
            }
        }
    } catch (SecurityException e) {
        Log.warning(e);
    }
    if (securityContext != null) {
        requestContext.setSecurityContext(securityContext);
    } else {
        Method method = resourceInfo.getResourceMethod();
        if (!method.isAnnotationPresent(PermitAll.class)) {
            Response.ResponseBuilder responseBuilder = Response.status(Response.Status.UNAUTHORIZED);
            if (!XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) {
                responseBuilder.header(WWW_AUTHENTICATE, BASIC_REALM);
            }
            throw new WebApplicationException(responseBuilder.build());
        }
    }
}
Also used : User(org.traccar.model.User) WebApplicationException(javax.ws.rs.WebApplicationException) SQLException(java.sql.SQLException) Method(java.lang.reflect.Method) Response(javax.ws.rs.core.Response) SecurityContext(javax.ws.rs.core.SecurityContext) PermitAll(javax.annotation.security.PermitAll)

Example 53 with SecurityContext

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

the class FF4jAuthorizationFilter method filter.

/**
 * Apply the filter ozz: check input request, validate or not with user auth
 *
 * @param containerRequest The request from Tomcat server
 */
@Override
public void filter(ContainerRequestContext containerRequest) throws IOException {
    String path = containerRequest.getUriInfo().getPath();
    log.debug("Entering authorization filter for <" + path + ">");
    // @Denyall anywhere => none shall pass => Error 403
    if (isDenyAll())
        forbidden();
    // THEN @PermitAll anywhere => everybodey pass
    if (isPermitAll())
        return;
    // Check @RoleAllowed against SecurityContext
    if (isRolesAllowed()) {
        SecurityContext sc = containerRequest.getSecurityContext();
        if (sc instanceof FF4jSecurityContext) {
            Set<String> expectedRoles = getRoles();
            FF4jSecurityContext fsc = (FF4jSecurityContext) sc;
            Set<String> permissions = fsc.getUserRoles();
            if (permissions != null) {
                for (String userPermission : permissions) {
                    if (expectedRoles.contains(userPermission)) {
                        return;
                    }
                }
            }
            log.warn("Request Forbidden : user role are " + permissions + " but target expected=" + expectedRoles);
            forbidden();
        }
    }
    return;
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext)

Example 54 with SecurityContext

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

the class StreamMetadataResourceImpl method getReaderGroup.

@Override
public void getReaderGroup(final String scopeName, final String readerGroupName, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
    long traceId = LoggerHelpers.traceEnter(log, "getReaderGroup");
    long requestId = requestIdGenerator.nextLong();
    try {
        restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofReaderGroupInScope(scopeName, readerGroupName), READ);
    } catch (AuthException e) {
        log.warn(requestId, "Get reader group for {} failed due to authentication failure.", scopeName + "/" + readerGroupName);
        asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
        LoggerHelpers.traceLeave(log, "getReaderGroup", traceId);
        return;
    }
    ClientFactoryImpl clientFactory = new ClientFactoryImpl(scopeName, this.localController, this.clientConfig);
    ReaderGroupManager readerGroupManager = new ReaderGroupManagerImpl(scopeName, this.localController, clientFactory);
    ReaderGroupProperty readerGroupProperty = new ReaderGroupProperty();
    readerGroupProperty.setScopeName(scopeName);
    readerGroupProperty.setReaderGroupName(readerGroupName);
    CompletableFuture.supplyAsync(() -> {
        ReaderGroup readerGroup = readerGroupManager.getReaderGroup(readerGroupName);
        readerGroupProperty.setOnlineReaderIds(new ArrayList<>(readerGroup.getOnlineReaders()));
        readerGroupProperty.setStreamList(new ArrayList<>(readerGroup.getStreamNames()));
        return Response.status(Status.OK).entity(readerGroupProperty).build();
    }, controllerService.getExecutor()).exceptionally(exception -> {
        log.warn(requestId, "getReaderGroup for {} failed with exception: ", readerGroupName, exception);
        if (exception.getCause() instanceof ReaderGroupNotFoundException) {
            return Response.status(Status.NOT_FOUND).build();
        } else {
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }).thenAccept(response -> {
        asyncResponse.resume(response);
        readerGroupManager.close();
        clientFactory.close();
        LoggerHelpers.traceLeave(log, "getReaderGroup", traceId);
    });
}
Also used : ApiV1(io.pravega.controller.server.rest.v1.ApiV1) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) TagLogger(io.pravega.common.tracing.TagLogger) RESTAuthHelper(io.pravega.shared.rest.security.RESTAuthHelper) LocalController(io.pravega.controller.server.eventProcessor.LocalController) StoreException(io.pravega.controller.store.stream.StoreException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) INTERNAL_NAME_PREFIX(io.pravega.shared.NameUtils.INTERNAL_NAME_PREFIX) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) AuthorizationResource(io.pravega.shared.security.auth.AuthorizationResource) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) CreateScopeRequest(io.pravega.controller.server.rest.generated.model.CreateScopeRequest) Collectors(java.util.stream.Collectors) CreateStreamRequest(io.pravega.controller.server.rest.generated.model.CreateStreamRequest) READER_GROUP_STREAM_PREFIX(io.pravega.shared.NameUtils.READER_GROUP_STREAM_PREFIX) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) StreamState(io.pravega.controller.server.rest.generated.model.StreamState) Response(javax.ws.rs.core.Response) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) Futures(io.pravega.common.concurrent.Futures) AuthException(io.pravega.auth.AuthException) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateStreamRequest(io.pravega.controller.server.rest.generated.model.UpdateStreamRequest) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) ScaleMetadata(io.pravega.controller.store.stream.ScaleMetadata) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) Status(javax.ws.rs.core.Response.Status) AuthorizationResourceImpl(io.pravega.shared.security.auth.AuthorizationResourceImpl) LoggerHelpers(io.pravega.common.LoggerHelpers) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ModelHelper(io.pravega.controller.server.rest.ModelHelper) ReaderGroupsList(io.pravega.controller.server.rest.generated.model.ReaderGroupsList) AuthHandlerManager(io.pravega.shared.rest.security.AuthHandlerManager) ReaderGroupsListReaderGroups(io.pravega.controller.server.rest.generated.model.ReaderGroupsListReaderGroups) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) ClientConfig(io.pravega.client.ClientConfig) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) ReaderGroup(io.pravega.client.stream.ReaderGroup) AuthException(io.pravega.auth.AuthException) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl)

Example 55 with SecurityContext

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

the class StreamMetadataResourceImpl method listStreams.

/**
 * Implementation of listStreams REST API.
 *
 * @param scopeName           The scope name of stream.
 * @param securityContext     The security for API access.
 * @param asyncResponse       AsyncResponse provides means for asynchronous server side response processing.
 */
@Override
public void listStreams(final String scopeName, final String filterType, final String filterValue, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
    long traceId = LoggerHelpers.traceEnter(log, "listStreams");
    long requestId = requestIdGenerator.nextLong();
    final Principal principal;
    final List<String> authHeader = getAuthorizationHeader();
    try {
        principal = restAuthHelper.authenticate(authHeader);
        restAuthHelper.authorize(authHeader, authorizationResource.ofStreamsInScope(scopeName), principal, READ);
    } catch (AuthException e) {
        log.warn(requestId, "List streams for {} failed due to authentication failure.", scopeName);
        asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
        LoggerHelpers.traceLeave(log, "listStreams", traceId);
        return;
    }
    boolean showOnlyInternalStreams = filterType != null && filterType.equals("showInternalStreams");
    boolean showStreamsWithTag = filterType != null && filterType.equals("tag");
    String tag;
    if (showStreamsWithTag && filterValue != null) {
        tag = filterValue;
        List<Stream> streams = new ArrayList<>();
        String finalTag = tag;
        localController.listStreamsForTag(scopeName, tag).collectRemaining(streams::add).thenCompose(v -> {
            List<CompletableFuture<ImmutablePair<Stream, StreamConfiguration>>> streamConfigFutureList = streams.stream().filter(stream -> {
                boolean isAuthorized = false;
                try {
                    isAuthorized = restAuthHelper.isAuthorized(authHeader, authorizationResource.ofStreamInScope(scopeName, stream.getStreamName()), principal, READ);
                } catch (AuthException e) {
                    log.warn(requestId, "List Streams with tag {} for scope {} failed due to authentication failure.", finalTag, scopeName);
                // Ignore. This exception occurs under abnormal circumstances and not to determine
                // whether the user is authorized. In case it does occur, we assume that the user
                // is unauthorized.
                }
                return isAuthorized;
            }).map(stream -> localController.getStreamConfiguration(scopeName, stream.getStreamName()).thenApply(config -> new ImmutablePair<>(stream, config))).collect(Collectors.toList());
            return Futures.allOfWithResults(streamConfigFutureList);
        }).thenApply(streamConfigPairs -> {
            StreamsList responseStreams = new StreamsList();
            responseStreams.setStreams(new ArrayList<>());
            streamConfigPairs.forEach(pair -> responseStreams.addStreamsItem(ModelHelper.encodeStreamResponse(pair.left.getScope(), pair.left.getStreamName(), pair.right)));
            log.info(requestId, "Successfully fetched streams for scope: {} with tag: {}", scopeName, finalTag);
            return Response.status(Status.OK).entity(responseStreams).build();
        }).exceptionally(exception -> {
            if (exception.getCause() instanceof StoreException.DataNotFoundException || exception instanceof StoreException.DataNotFoundException) {
                log.warn(requestId, "Scope name: {} not found", scopeName);
                return Response.status(Status.NOT_FOUND).build();
            } else {
                log.warn(requestId, "listStreams for {} with tag {} failed with exception: {}", scopeName, finalTag, exception);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "listStreams", traceId));
    } else {
        controllerService.listStreamsInScope(scopeName, requestId).thenApply(streamsList -> {
            StreamsList streams = new StreamsList();
            streams.setStreams(new ArrayList<>());
            streamsList.forEach((stream, config) -> {
                try {
                    if (restAuthHelper.isAuthorized(authHeader, authorizationResource.ofStreamInScope(scopeName, stream), principal, READ)) {
                        // otherwise display the regular user created streams.
                        if (!showOnlyInternalStreams ^ stream.startsWith(INTERNAL_NAME_PREFIX)) {
                            streams.addStreamsItem(ModelHelper.encodeStreamResponse(scopeName, stream, config));
                        }
                    }
                } catch (AuthException e) {
                    log.warn(requestId, "Read internal streams for scope {} failed due to authentication failure.", scopeName);
                // Ignore. This exception occurs under abnormal circumstances and not to determine
                // whether the user is authorized. In case it does occur, we assume that the user
                // is unauthorized.
                }
            });
            log.info(requestId, "Successfully fetched streams for scope: {}", scopeName);
            return Response.status(Status.OK).entity(streams).build();
        }).exceptionally(exception -> {
            if (exception.getCause() instanceof StoreException.DataNotFoundException || exception instanceof StoreException.DataNotFoundException) {
                log.warn(requestId, "Scope name: {} not found", scopeName);
                return Response.status(Status.NOT_FOUND).build();
            } else {
                log.warn(requestId, "listStreams for {} failed with exception: {}", scopeName, exception);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "listStreams", traceId));
    }
}
Also used : ApiV1(io.pravega.controller.server.rest.v1.ApiV1) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ReaderGroupNotFoundException(io.pravega.client.stream.ReaderGroupNotFoundException) TagLogger(io.pravega.common.tracing.TagLogger) RESTAuthHelper(io.pravega.shared.rest.security.RESTAuthHelper) LocalController(io.pravega.controller.server.eventProcessor.LocalController) StoreException(io.pravega.controller.store.stream.StoreException) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) ReaderGroupProperty(io.pravega.controller.server.rest.generated.model.ReaderGroupProperty) INTERNAL_NAME_PREFIX(io.pravega.shared.NameUtils.INTERNAL_NAME_PREFIX) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) AuthorizationResource(io.pravega.shared.security.auth.AuthorizationResource) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) CreateScopeRequest(io.pravega.controller.server.rest.generated.model.CreateScopeRequest) Collectors(java.util.stream.Collectors) CreateStreamRequest(io.pravega.controller.server.rest.generated.model.CreateStreamRequest) READER_GROUP_STREAM_PREFIX(io.pravega.shared.NameUtils.READER_GROUP_STREAM_PREFIX) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) StreamState(io.pravega.controller.server.rest.generated.model.StreamState) Response(javax.ws.rs.core.Response) ScopesList(io.pravega.controller.server.rest.generated.model.ScopesList) Futures(io.pravega.common.concurrent.Futures) AuthException(io.pravega.auth.AuthException) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateStreamRequest(io.pravega.controller.server.rest.generated.model.UpdateStreamRequest) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) ScaleMetadata(io.pravega.controller.store.stream.ScaleMetadata) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) Status(javax.ws.rs.core.Response.Status) AuthorizationResourceImpl(io.pravega.shared.security.auth.AuthorizationResourceImpl) LoggerHelpers(io.pravega.common.LoggerHelpers) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) ScopeProperty(io.pravega.controller.server.rest.generated.model.ScopeProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ModelHelper(io.pravega.controller.server.rest.ModelHelper) ReaderGroupsList(io.pravega.controller.server.rest.generated.model.ReaderGroupsList) AuthHandlerManager(io.pravega.shared.rest.security.AuthHandlerManager) ReaderGroupsListReaderGroups(io.pravega.controller.server.rest.generated.model.ReaderGroupsListReaderGroups) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) ClientConfig(io.pravega.client.ClientConfig) StreamsList(io.pravega.controller.server.rest.generated.model.StreamsList) ArrayList(java.util.ArrayList) AuthException(io.pravega.auth.AuthException) StoreException(io.pravega.controller.store.stream.StoreException) CompletableFuture(java.util.concurrent.CompletableFuture) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Stream(io.pravega.client.stream.Stream) Principal(java.security.Principal)

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