Inspect request body within a spring security filter - spring

Basic Spring Security is great as it comes with WebSecurity (preventing malformed URLs) along with setting up authentication and authorization.
As part of authenticating my web request, the digest of the request body needs to be verified against the digest value passed in the http header. Setting up the Spring Security filter, forces my auth filter to process a firewalled request. The firewalled request doesn't seem to expose the request body to the filter.
What is the correct way to set up the Spring Security filter so that I can inspect the request body?
Thanks!

In Spring Security there are many filter classes built in for to be extended and used for specific purposes. As in my experience most of (or all of them) have methods with overloads which have access to,
HttpServletRequest request, HttpServletResponse response
as method arguments, so that those can be used inside the method.
When the filter class is met with any request, these variables are then populated with related data thus the code inside the methods output as expected.

Related

GraphQL Subscriptions - Spring Boot Websocket Authentication

We are using the Netflix DGS framework to build our backend to provide a GraphQL API.
In addition to that we use Keykloak as an identity provider which comes with a handy Spring module to add support for authentication and authorization out of the box.
Every request contains a JWT token, which gets validated and from there a SecurityContext object is being generated which is then available in every endpoint.
This is working great for HTTP requests. GraphQL queries and mutations are sent via HTTP, therefore no problem here.
Subscriptions on the other hand use the web socket protocol. A WS request does not contain additional headers, therefore no JWT token is sent with the request.
We can add the token via a payload, the question is now how to set up a Spring Security Filter which creates a Security Context out of the payload.
I guess this is rather Spring specific, basically a filter which intercepts any web socket request (ws://... or wss://...) is needed.
Any help or hint is very much appreciated!
The only way to use headers in web socket messages is in the connection_init message. the headers will be sent by the client in the payload of the message.
The solution I propose is done in 2 steps (We will assume that the name of the header element is "token"):
Intercept the connection_init message, then force the insertion of a new element (token) in the subscription request.
Retrieve the element (token) of the header during the interception of the subscription and feed the context.
Concretely, the solution is the implementation of WebSocketGraphQlInterceptor interface
#Configuration
class SubscriptionInterceptor implements WebSocketGraphQlInterceptor {
#Override
public Mono<Object> handleConnectionInitialization(WebSocketSessionInfo sessionInfo, Map<String, Object> connectionInitPayload) {
sessionInfo.getHeaders().add("token", connectionInitPayload.get("token").toString());
return Mono.just(connectionInitPayload);
}
#Override
public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) {
List<String> token = request.getHeaders().getOrEmpty("token");
return chain.next(request).contextWrite(context -> context. Put("token", token.isEmpty() ? "" : token.get(0)));
}
}

OAuth in Spring Security 5.2.x: Store userInfo response

We are running an API on Sping Boot 2.2 and are consequently using Sping Security 5.2. In securing this API with OAuth, we are using the new features built into Spring Security (since the Spring Security OAuth project is now deprecated). We are using opaque tokens and (as indicated by the documentation) have a security config of the following form:
#Configuration
public static class OAuthWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().mvcMatchers("/path/to/api/**").hasAuthority(CUSTOM_SCOPE)
.oauth2ResourceServer().opaqueToken().introspector(opaqueTokenIntrospector());
}
}
Here opaqueTokenIntrospector() is a bean which performs the following tasks:
Send a request to the introspection endpoint to get the full token.
Also send a request to the userinfo endpoint to get additional info about the user from the IDP.
Map some of this additional info into custom spring roles and add these roles to the authenticated user.
The way this configuration is set up, each request to the API comes with two additional requests: one to the introspection endpoint and one to the userinfo endpoint. It would be better to save on some of these if a user performs successive requests to the API.
Is it possible to save the result of the opaqueTokenIntrospector() in the session of the user? This way the whole flow of the bean need only be done once per user, saving on redundant requests.
This is a common requirement when you get beyond basic APIs. Use a claims caching solution, which is an API gateway pattern:
When a token is first received do the lookups and save them into an object:
Token claims
User info claims
App specific claims
Then cache the results against the token, so that subsequent requests with the same token are fast:
Use a thread safe cache - my preference is to use an in memory one
Use the SHA256 hash of the access token as the key
Use the serialized claims as the value
This probably goes beyond Spring's default behaviour, but you can customise it.
I have a Java sample that does this - here are a couple of links, though my sample is quite a complex one:
Custom Authorizer Class
Caching Class
Java Write Up

How does spring security maintain authentication information between request?

How does spring security maintain authentication info between requests?
Does it use any thing similar to jSessionId or uses an entirely different mechanism.
Further, I see that the AbstractSecurityInterceptor (I mean, any of it's implementations) is responsible for intercepting the incoming request and verify if a request is already authorized using Authentication.isAuthenticated() and then depending on the condition either validate the request or send the Authentication request to an AuthenticationManager Implementation. So, in other words, how does AbstractSecurityInterceptor differentiate between first request and subsequent request.
Spring Security uses a SecurityContextRepository to store and retrieve the SecurityContext for the current security session.
The default implementation is the HttpSessionSecurityContextRepository which utilizes the javax.servlet.http.HttpSession to store/retrieve the SecurityContext.
The underlying servlet container will obtain the correct HttpSession for the incoming request, generally due to a session identifier being passed in a cookie or request parameter. For Spring Security it doesn't matter as that is thus loaded of to the underlying servlet container.

Using Server Request and Response filters for ThreadLocal storage in a RestEasy based service

I am currently working on a RESTeasy based RESTful service. I have a filter class which serves as a server request filter as well as a server response filter (i.e. it implements ContainerRequestFilter and ContainerResponseFilter interfaces).
At the beginning of the request, I use the filter to put an object into ThreadLocal. This object is used by the resources throughout the request. At the end of the request, before sending out the response, the filter removes the object from ThreadLocal.
My question is that is there a guarantee that the the request filter, the resource and the response filter will all execute in the same thread? Is there a possibility that after the request filter puts the object into ThreadLocal, a different thread will execute the request (and thus not have access to the object)?
I was sure that this was the case but then I saw this http://jersey.576304.n2.nabble.com/Does-filter-method-of-ContainerRequestFilter-run-in-resource-method-thread-td7582648.html (official Jersey forum) and now I have doubts.
javax.ws.rs.container.ContainerRequestContext.setProperty(...)
and
javax.ws.rs.container.ContainerRequestContext.getProperty(...)
are probably the right approach. The javadoc states:
In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

Spring Data REST CORS - how to handle preflight OPTIONS request?

I'm using Spring Data REST to build a RESTful API. Until now my HTML GUI for this RESTful service was served from the same Tomcat and I had no problems wit Cross Origin requests.
Now I want to serve the static files from a different server. This means the API is on another domain/port. Browsers will send the OPTIONS request to get the Access-Control headers from the server. Unfortunately Spring Data REST does not handle those OPTIONS requests and even returns a HTTP 500.
I tried creating a custom controller that handles all OPTIONS requests
#Controller
#RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
public class OptionsController {
#RequestMapping
public ResponseEntity options() {
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
Which worked for OPTIONS, but then all other requests (like GET) ceased to work.
OPTIONS requests are switched on via the dispatchOptionsRequest dispatcher servlet parameter.
tl;dr: currently Spring Data REST does not answer OPTIONS requests at all.
It might be worth opening a ticket in our JIRA.
Browsers will send the OPTIONS request to get the Access-Control headers from the server.
Is that specified somewhere? If so, it would be cool if the ticket description included a link to that spec.
A few comments regarding your approach for a workaround:
#RequestMapping on the controller method overrides the method attribute and expectedly now matches all HTTP methods, which is why you see all requests intercepted. So you need to define OPTIONS as HTTP method there, too (or maybe instead of in the class mapping).
You're not returning any Allow header which is the whole purpose of OPTIONS in the first place.
I wonder if the approach in general makes sense as it'll be hard to reason about the supported HTTP methods in general.
Just set the parameter dispatchOptionsRequest to true into the dispatcher to process the Options method calls, into the implementation of the WebApplicationInitializer.
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(applicationContext));
dispatcher.setInitParameter("dispatchOptionsRequest", "true");
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Resources