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());
}
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"));
}
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");
}
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();
}
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);
}
Aggregations