Cookie management in Quarkus - quarkus

How do I configure cookie management in the Quarkus rest client?
I am building a client to an API that sets a session cookie on login and then uses that session cookie for auth - a pretty standard stateful API.
It seems that with default behaviour with #RegisterRestClient does not preserve cookies between requests.
Having a dig, it seems that ResteasyClientBuilderImpl has a field cookieManagementEnabled which is false by default. This then disables cookies in ClientHttpEngineBuilder43 by default too.
I also found that if you use the async engine (useAsyncHttpEngine) this sync engine builder is not used and cookie management is also enabled.
The only way I found to configure the ResteasyClientBuilder underlying the RestClientBuilder was to use a RestClientBuilderListener. However, the plot thickens here.
There is a method in RestClientBuilder - property(String name, Object value) - that, in the case of Quarkus at least will delegate to the underlying ResteasyClientBuilder
if (name.startsWith(RESTEASY_PROPERTY_PREFIX)) {
// Makes it possible to configure some of the ResteasyClientBuilder delegate properties
However, a few lines down
Method builderMethod = Arrays.stream(ResteasyClientBuilder.class.getMethods())
.filter(m -> builderMethodName.equals(m.getName()) && m.getParameterTypes().length >= 1)
.findFirst()
.orElse(null);
i.e. it will only allows for non-nullary methods to be called. And to enable cookie management I need to call enableCookieManagement - which has no arguments.
So, the only way I have found to enable cookie management is:
class CookieConfigBuilderListener : RestClientBuilderListener {
override fun onNewBuilder(builder: RestClientBuilder) {
val builderImpl = builder as QuarkusRestClientBuilder
val delegateField = QuarkusRestClientBuilder::class.java.getDeclaredField("builderDelegate")
delegateField.isAccessible = true
val resteasyBuilder = delegateField.get(builderImpl) as ResteasyClientBuilder
resteasyBuilder.enableCookieManagement()
}
}
This is obviously far from ideal, not least because it uses reflection in a GraalVM native image setting and therefore will likely also require me to enable reflection on QuarkusRestClientBuilder.
So, back to the original question, how do I enable cookie management in the Quarkus rest client?

Related

Spring-security 6 - 403 denied because AuthenticationProvider not called

I've recently upgraded a project from using spring-security 6.0.0-M6 to 6.0.0, gradle config if you want to see it.
This project does not use spring-boot.
Context
My securityFilterChain is configured via code and looks approximately like this:
http.
authenticationManager(authnManager).
securityContext().securityContextRepository(securityRepo).
and().
authorizeRequests(). // <-- DEPRECATED
requestMatchers(RAID_V2_API + "/**").fullyAuthenticated().
The full codebase, starting with the FilterChain config, is publicly available.
Note that usage of WebSecurityConfigurerAdapter is deprecated, and I have not been using it since the original usage of 6.0.0-M6. So calling stuff like WebSecurityConfigurerAdapter.authenticationManagerBean() won't work.
This code works fine, but the call to authorizeRequests() causes a deprecation warning that I want to get rid of.
Problem
The deprecation tag says that I should use authorizeHttpRequests() instead, but when I do that - requests that require authorization (via the fullyAuthenticated() specification above) will be denied with a 403 error.
Analysis
It seems this happens because my AuthenticationProvider instances aren't being called,
because the ProviderManager isn't being called. Since the AuthnProviders don't get called, the security context still contains the pre-auth token instead of a verified post-auth token, so the eventual call to AuthorizationStrategy.isGranted() ends up calling isAuthenticated() on the pre-auth token, which (correctly) returns false and the request is denied.
Question
How do I use the authorizeHttpRequests() method but still have the ProviderManager be called so that my security config works?
My workaround is just to ignore the deprecation warning.
First, your security configuration does not specify any kind of authentication, like httpBasic, formLogin, etc. The AuthenticationManager is invoked by the filters created by those authentication mechanisms in order to authenticate credentials.
Second, the application is probably unwittingly relying on FilterSecurityInterceptor (authorizeRequests) to authenticate the user, which is not supported with authorizeHttpRequests. You need to declare an auth mechanism that collects credentials from the request and authenticates the user.
Because you are using JWT, you might want to consider Spring Security's OAuth2 Resource Server support. You can also refer to our samples repository in order to help you with sample configurations.
Here's a rough outline of what I did to to implement the "just use the resource server" suggestion from the answer.
include the oauth2-resource-server libraries in the build.
create an AuthenticationManagerResolver that replaces what the SecuritycontextRepository and the FilterSecurityInterceptor used to do:
#Bean
public AuthenticationManagerResolver<HttpServletRequest>
tokenAuthenticationManagerResolver(
AuthenticationProvider authProvider
) {
return (request)-> {
return authProvider::authenticate;
};
}
change AuthenticationProvider implementations to use the BearerTokenAuthenticationToken class as the pre-auth token, it still works basically the same way it used to: verifying the pre-auth token and returning a post-auth token.
hook up the new resolver class in the securityFilterChain config by replacing the old securityContextRepository() config with the new authenticationManagerResolver() config, which passes in the resolver created in step 2:
http.oauth2ResourceServer(oauth2 ->
oauth2.authenticationManagerResolver(tokenAuthenticationManagerResolver) );
I like this new approach because it makes it more obvious how the security chain works.
It's nice to replace the custom pre-auth token implementation with the built-in class too.
Note that it's likely this config can be simplified, but I needed the custom resolver since the project uses different types of bearer token depending on the endpoint called. Pretty sure the auth providers don't need to be AuthenticationProvider any more; the lambda function returned from the resolver serves that purpose - they can probably just be random spring components and as long as the method is SAM-type compatible.
The spring-security multi-tenancy doco was helpful for this.

Reactive rest client headers injection in Quarkus

I am following the guide of the new quarkus-resteasy-reactive-jackson extension to use it in an existing Quarkus application deployed in production.
In the Custom headers support section it's introduced the ClientHeadersFactory interface to allow injecting headers in a request, but you are forced to return a sync response. One can not use Uni<MultivaluedMap<String, String>>, which is of what is desired in my case, because I need to add a token in the header, and this token is retrieved by a request to another rest endpoint that returns a Uni<Token>.
How can I achieve this in the new implementation? If not possible, is there a workaround?
It's not possible to use Uni<MultivaluedMap<...>> in ClientHeadersFactory in Quarkus 2.2.x (and older versions). We may add such a feature in the near future.
Currently, you can #HeaderParam directly. Your code could probably look as follows:
Uni<String> token = tokenService.getToken();
token.onItem().transformToUni(tokenValue -> client.doTheCall(tokenValue));
Where the client interface would be something like:
#Path("/")
public interface MyClient {
#GET
Uni<Foo> doTheCall(#HeaderParam("token") String tokenValue);
}

Spring Boot 2.3.4: Bug with JwtValidators.createDefaultWithIssuer(String)?

I found an odd behavior with JWT parsing and JwtValidators.
Scenario:
Spring Boot OIDC client (for now a tiny web app, only displaying logged in user and some OIDC objects provided by Spring)
Custom JwtDecoderFacotry<ClientRegistration> for ID-Token validation
JwtValidatorFactory based on JwtValidators.createDefaultWithIssuer(String)
This worked well with Spring Boot version <= 2.2.10.
Debugging:
NimbusJwtDecoder (JAR spring-security-oauth2-jose) uses claim set converters. The 'iss' (issuer) claim is handled as URL.
JwtIssuerValidator (internally created by JwtValidators.createDefaultWithIssuer(String)) wraps a JwtClaimValidator<String>.
this one finally calls equals() that is always false - it compares String with URL.
My current workaround is not calling JwtValidators.createDefaultWithIssuer() but just using the validators new JwtTimestampValidator() and an own implementation of OAuth2TokenValidator<Jwt> (with wrapping JwtClaimValidator<URL>).
Anyone else having trouble with this?
--Christian
It's a bug. Pull Request is created.

How to properly provide Authentication object (SecurityContext) to application itself?

Most of my application is secured with method level security (AspectJ, but it doesn't matter) and now that I am trying to call some code from within application itself (not controllers, but e.g. EventListener) I can't help to wonder if Spring Security provides some out-of-box way of giving Authentication object to the application itself, otherwise I cannot get past my method security since application has null security objects (Authentication in SecurityContext, if it even exists - depends on situation, You might have to init it first).
Sure I can do something like this (just before running relevant code):
UserDetails ud = User.builder()
.username("APPLICATION")
.password("APPLICATION")
.roles("APPLICATION")
.build();
Authentication auth = new UsernamePasswordAuthenticationToken(ud, ud.getPassword(), ud.getAuthorities());
SecurityContextHolder.getContext()
.setAuthentication(auth);
But is it safe to do this in deployment (security-wise)?
Is there any guarantee on which thread will own this SecurityContext? What about other threads and their tasks?
Once set, can it stay there? Will it for the rest of app's run (can be days/months), context could be reloaded, etc. I lack deep Spring knowledge to know what happens Thread-wise inside Spring.

Enforce separate sessions for different tabs in spring security

I am using spring security v 3.1.3 in my web application. The app has a single entry login form customized with custom-filter in spring security. For now, my configurations are allowing a user to automatically log in the app if he opens the URL from a different tab in same browser, which is the default behavior of spring security session management.
I want to ensure that whenever a user log into the application, the session should not get shared across different tabs. On opening a new tab, he should get login page and logging in would create a new session in the same browser. For now i could not find any way to do this with spring security framework. I wouldn't mind integrating JsessionID in URLs, but it would be better if there is another way.
This is not a limitation on Spring Security, this is a general limitation of how the browsers work with cookies; if you set a cookie it's going to be shared by all tabs.
Said that the only reasonable option I can think of right now would be to include the session id in the URL as you suggested.
You can make use of HeaderWebSessionIdResolver.
Spring uses CookieWebSessionIdResolver by default.
To make use of it, use a random sessionId and save it in session storage, and send it along with your headers. This will vary across tabs, and will provide you with different web sessions.
val headerName = "SomeHeaderName"
#Configuration
class SessionConfig {
#Bean
fun headerWebSessionIdResolver(): WebSessionIdResolver {
return HeaderWebSessionIdResolver().apply {
headerName = headerName
}
}
#Bean
fun webSessionManager(webSessionIdResolver: WebSessionIdResolver): DefaultWebSessionManager {
return DefaultWebSessionManager().apply {
sessionIdResolver = webSessionIdResolver
}
}
}

Resources