Search in sources :

Example 11 with SecurityContext

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

the class JaxrsModuleTest method testGetter.

@Test
public void testGetter() {
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    JaxrsModule module = new JaxrsModule(securityContext);
    Assert.assertEquals("jaxrs", module.getModuleName());
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) JaxrsModule(io.crnk.rs.internal.JaxrsModule) Test(org.junit.Test)

Example 12 with SecurityContext

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

the class JaxrsModuleTest method checkSecurityProviderRegistered.

@Test
public void checkSecurityProviderRegistered() {
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    JaxrsModule module = new JaxrsModule(securityContext);
    CrnkBoot boot = new CrnkBoot();
    boot.addModule(module);
    boot.boot();
    SecurityProvider securityProvider = boot.getModuleRegistry().getSecurityProvider();
    Assert.assertNotNull(securityProvider);
    Mockito.when(securityContext.isUserInRole("admin")).thenReturn(true);
    Assert.assertTrue(securityProvider.isUserInRole("admin"));
    Assert.assertFalse(securityProvider.isUserInRole("other"));
}
Also used : CrnkBoot(io.crnk.core.boot.CrnkBoot) SecurityContext(javax.ws.rs.core.SecurityContext) JaxrsModule(io.crnk.rs.internal.JaxrsModule) SecurityProvider(io.crnk.core.engine.security.SecurityProvider) Test(org.junit.Test)

Example 13 with SecurityContext

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

the class FF4jAuthenticationFilter 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 method = containerRequest.getMethod();
    String path = containerRequest.getUriInfo().getPath();
    log.debug("Entering security filter for <" + path + ">");
    // We do allow wadl to be retrieve
    if (method.equals("GET") && (path.equals("application.wadl") || path.equals("application.wadl/xsd0.xsd"))) {
        log.info("Accessing schema and wadl ok");
        return;
    }
    // Get the authentification passed in HTTP headers parameters
    String auth = containerRequest.getHeaderString(HEADER_AUTHORIZATION);
    if (auth == null) {
        handleUnAuthorized("<p>'authorization' parameter is required in header  for authentication (HTTP-Basic or ApiKey)</p>");
    }
    // Identification of an Application with its api key
    if (auth.contains(PARAM_AUTHKEY)) {
        auth = auth.replaceFirst(PARAM_AUTHKEY + "=", "");
        // Checking api Key
        if (!apiConfig.getApiKeys().contains(auth)) {
            handleUnAuthorized("The api key provided '" + auth + "' is invalid ");
        }
        // Positionning Roles
        Set<String> perms = apiConfig.getPermissions().get(auth);
        SecurityContext sc = new FF4jSecurityContext(auth, FF4jSecurityContext.AUTH_SCHEME_APIKEY, perms);
        containerRequest.setSecurityContext(sc);
        log.info("Client successfully logged with an ApiKey");
        return;
    }
    // Identification of a final user in HTTP-BASIC MODE
    if (auth.toUpperCase().contains("BASIC")) {
        byte[] decodedBytes = Base64.decode(auth.replaceFirst("[B|b]asic ", "").getBytes());
        String[] lap = new String(decodedBytes).split(":", 2);
        if (lap == null || lap.length != 2) {
            handleUnAuthorized("Invalid BASIC Token, cannot parse");
        }
        // Validation login/password
        String expectedPassword = apiConfig.getUsers().get(lap[0]);
        if (expectedPassword == null || !(lap[1].equals(expectedPassword))) {
            handleUnAuthorized("<p>Invalid username or password.</p>");
        }
        // Positionning Roles
        Set<String> perms = apiConfig.getPermissions().get(lap[0]);
        log.info(Arrays.toString(perms.toArray()));
        SecurityContext sc = new FF4jSecurityContext(lap[0], FF4jSecurityContext.AUTH_SCHEME_BASIC, perms);
        containerRequest.setSecurityContext(sc);
        log.info("Client successfully logged with a user/pasword pair ");
        return;
    }
    handleUnAuthorized("Cannot parse authorisation header attribute, valid are basic and apiKey");
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext)

Example 14 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project uploader by smoketurner.

the class BatchResource method upload.

@POST
@Consumes(MediaType.WILDCARD)
public Response upload(@Context SecurityContext context, InputStream input) {
    final Optional<String> customerId = AuthHandler.getCustomerId(context.getUserPrincipal());
    if (!customerId.isPresent()) {
        throw new WebApplicationException("No customerId found in request");
    }
    final Batch batch;
    try {
        batch = Batch.create(customerId.get());
    } catch (IOException e) {
        LOGGER.error("Unable to create batch", e);
        throw new WebApplicationException("Unable to create batch", e);
    }
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
        reader.lines().map(line -> line.getBytes(StandardCharsets.UTF_8)).forEach(line -> {
            try {
                batch.add(line);
            } catch (IOException e) {
                LOGGER.error("Unable to process line", e);
            }
        });
    } catch (IOException e) {
        LOGGER.error("Unable to read input", e);
        throw new WebApplicationException("Unable to read input", e);
    }
    uploader.upload(batch);
    return Response.accepted().build();
}
Also used : Uploader(com.smoketurner.uploader.core.Uploader) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Logger(org.slf4j.Logger) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) AuthHandler(com.smoketurner.uploader.handler.AuthHandler) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Batch(com.smoketurner.uploader.core.Batch) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) BufferedReader(java.io.BufferedReader) Nonnull(javax.annotation.Nonnull) InputStream(java.io.InputStream) WebApplicationException(javax.ws.rs.WebApplicationException) InputStreamReader(java.io.InputStreamReader) Batch(com.smoketurner.uploader.core.Batch) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 15 with SecurityContext

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

the class AuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    log.debug("Authentication check for {}", requestContext.getUriInfo().getPath());
    HttpRequest httpRequest = ResteasyProviderFactory.getContextData(HttpRequest.class);
    ResourceInfo resourceInfo = ResteasyProviderFactory.getContextData(ResourceInfo.class);
    Method method = resourceInfo.getResourceMethod();
    SecurityHole hole = method.getAnnotation(SecurityHole.class);
    Principal principal = null;
    if (hole != null && hole.anon()) {
        principal = new NoAuthPrincipal();
    } else if (resourceInfo.getResourceClass().equals(ApiListingResource.class)) {
        log.debug("Swagger API request made; no principal required.");
        principal = new NoAuthPrincipal();
    } else {
        for (AuthProvider provider : providers) {
            principal = provider.getPrincipal(httpRequest);
            if (principal != null) {
                log.debug("Establishing principal with {}", provider.getClass().getName());
                break;
            }
        }
    }
    /* At this point, there is no provider that has given a valid principal,
         * so we use the NoAuthPrincipal here if it is allowed. */
    if (principal == null) {
        if (hole != null && hole.noAuth()) {
            log.debug("No auth allowed for resource; setting NoAuth principal");
            principal = new NoAuthPrincipal();
        } else if (!config.getBoolean(ConfigProperties.AUTH_OVER_HTTP) && !request.isSecure()) {
            throw new BadRequestException("Please use SSL when accessing protected resources");
        } else {
            throw new NotAuthorizedException("Invalid credentials.");
        }
    }
    SecurityContext securityContext = new CandlepinSecurityContext(principal);
    requestContext.setSecurityContext(securityContext);
    // Push the principal into the context for the PrincipalProvider to access directly
    ResteasyProviderFactory.pushContext(Principal.class, principal);
}
Also used : HttpRequest(org.jboss.resteasy.spi.HttpRequest) ResourceInfo(javax.ws.rs.container.ResourceInfo) SecurityHole(org.candlepin.common.auth.SecurityHole) NoAuthPrincipal(org.candlepin.auth.NoAuthPrincipal) ApiListingResource(io.swagger.jaxrs.listing.ApiListingResource) SecurityContext(javax.ws.rs.core.SecurityContext) BadRequestException(org.candlepin.common.exceptions.BadRequestException) AuthProvider(org.candlepin.auth.AuthProvider) Method(java.lang.reflect.Method) NotAuthorizedException(org.candlepin.common.exceptions.NotAuthorizedException) Principal(org.candlepin.auth.Principal) NoAuthPrincipal(org.candlepin.auth.NoAuthPrincipal)

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