use of javax.ws.rs.core.SecurityContext in project traccar by tananaev.
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());
}
}
}
use of javax.ws.rs.core.SecurityContext in project iaf by ibissource.
the class AuthorizationFilter method filter.
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
SecurityContext securityContext = requestContext.getSecurityContext();
if (securityContext.getUserPrincipal() == null) {
// No userPrincipal, authentication is disabled.
return;
}
if (requestContext.getMethod().equalsIgnoreCase("OPTIONS")) {
// Preflight in here?
return;
}
Message message = JAXRSUtils.getCurrentMessage();
Method method = (Method) message.get("org.apache.cxf.resource.method");
if (method == null) {
log.error("unable to fetch resource method from CXF Message");
requestContext.abortWith(SERVER_ERROR);
return;
}
if (method.isAnnotationPresent(DenyAll.class)) {
// Functionality has been disallowed.
requestContext.abortWith(FORBIDDEN);
return;
}
if (method.isAnnotationPresent(PermitAll.class)) {
// No authorization required.
return;
}
// Presume `PermitAll` when RolesAllowed annotation is not set
if (method.isAnnotationPresent(RolesAllowed.class)) {
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
log.info("checking authorisation for user [" + securityContext.getUserPrincipal().getName() + "] on uri [" + method.getAnnotation(javax.ws.rs.Path.class).value() + "] required roles " + rolesSet.toString());
if (!doAuth(securityContext, rolesSet)) {
requestContext.abortWith(FORBIDDEN);
return;
}
}
}
use of javax.ws.rs.core.SecurityContext in project keycloak by keycloak.
the class JaxrsBearerTokenFilterImpl method filter.
// REQUEST HANDLING
@Override
public void filter(ContainerRequestContext request) throws IOException {
SecurityContext securityContext = getRequestSecurityContext(request);
JaxrsHttpFacade facade = new JaxrsHttpFacade(request, securityContext);
if (handlePreauth(facade)) {
return;
}
KeycloakDeployment resolvedDeployment = deploymentContext.resolveDeployment(facade);
nodesRegistrationManagement.tryRegister(resolvedDeployment);
bearerAuthentication(facade, request, resolvedDeployment);
}
use of javax.ws.rs.core.SecurityContext in project ff4j by ff4j.
the class FF4jSecurityContextFilter method filter.
/**
* Apply the filter : check input request, validate or not with user auth
*
* @param containerRequest
* The request from Tomcat server
*/
@Override
public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException {
String method = containerRequest.getMethod();
String path = containerRequest.getPath(true);
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 containerRequest;
}
// Get the authentification passed in HTTP headers parameters
String auth = containerRequest.getHeaderValue(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 (!securityConfig.getApiKeys().contains(auth)) {
handleUnAuthorized("The api key provided '" + auth + "' is invalid ");
}
// Positionning Roles
Set<String> perms = securityConfig.getPermissions().get(auth);
SecurityContext sc = new FF4jSecurityContext(auth, PARAM_AUTHKEY, perms);
containerRequest.setSecurityContext(sc);
log.info("Client successfully logged with an ApiKey");
return containerRequest;
}
// Identification of a final user in HTTP-BASIC MODE
if (auth.toUpperCase().contains("BASIC")) {
byte[] decodedBytes = Base64.decode(auth.replaceFirst("[B|b]asic ", ""));
String[] lap = new String(decodedBytes).split(":", 2);
if (lap == null || lap.length != 2) {
handleUnAuthorized("Invalid BASIC Token, cannot parse");
}
// Validation login/password
String expectedPassword = securityConfig.getUsers().get(lap[0]);
if (expectedPassword == null || !(lap[1].equals(expectedPassword))) {
handleUnAuthorized("<p>Invalid username or password.</p>");
}
// Positionning Roles
Set<String> perms = securityConfig.getPermissions().get(lap[0]);
SecurityContext sc = new FF4jSecurityContext(lap[0], "BASIC", perms);
containerRequest.setSecurityContext(sc);
log.info("Client successfully logged with a user/pasword pair ");
return containerRequest;
}
handleUnAuthorized("Cannot parse authorisation header attribute, valid are basic and apiKey");
return null;
}
use of javax.ws.rs.core.SecurityContext in project minijax by minijax.
the class MinijaxApplication method checkSecurity.
private void checkSecurity(final MinijaxRequestContext context) {
final Annotation a = context.getResourceMethod().getSecurityAnnotation();
if (a == null) {
return;
}
final Class<?> c = a.annotationType();
if (c == PermitAll.class) {
return;
}
if (c == DenyAll.class) {
throw new ForbiddenException();
}
if (c == RolesAllowed.class) {
final SecurityContext security = context.getSecurityContext();
if (security == null || security.getUserPrincipal() == null) {
throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).build());
}
boolean found = false;
for (final String role : ((RolesAllowed) a).value()) {
if (security.isUserInRole(role)) {
found = true;
break;
}
}
if (!found) {
throw new ForbiddenException();
}
}
}
Aggregations