Handling token response in spring oauth2 client - spring

I am using Spring Cloud Gateway as a API Gateway for our system. We would like to delegate all authentication (oauth) to that component. I was looking at the source code of Spring Oauth2 Client but I don't see any place where I can "plug in" to do what I need.
I would like to catch the moment, when the code exchange is successful and make a redirect with id_token and refresh_token in cookie or query param. We don't store any session as well - whole authentication is meant to stateless.
I am configuring SecurityWebFilterChain (security for WebFlux) like this:
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(Customizer.withDefaults())
.oauth2Login();
http.csrf().disable();
return http.build();
}
I tried to use successHandler
.oauth2Login(c -> c.authenticationSuccessHandler(successHandler));, but in that moment I don't access to refresh_token (have only WebFilterExchange, Authentication in arguments) and I am not even sure how should I perform the redirect form that place.
Is there any way to achieve this?

Related

Reactive Spring: How to pass Access Token from OAuth 2.0 Authorization Code Flow to scheduled task

I'm trying to build an application that periodically fetches data from a Third-Party API that demands a reCAPTCHA protected OAuth 2.0 Authorization Code Flow with PKCE for authentication.
I guess, it wouldn't be a big deal to implement the authorization protocol manually but I'm willing to do that using the Spring Security OAuth Client in the reactive manner.
The goal is to have a scheduled task that fetches the data from the API only being blocked until I manually open up a login page (currently a REST endpoint) in the browser that forwards me to the login page of the API vendor. After successful authentication, the scheduled task should also be able to access the API.
Currently the class structure looks like this:
MyController#showData and MyScheduler#fetchData both call ApiClient#retrieveData which does the final API call using the reactive WebClient from Spring.
The WebClient configuration looks like this:
#Configuration
#EnableWebFluxSecurity
class WebClientConfiguration {
#Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegs,
ReactiveOAuth2AuthorizedClientService authClientService) {
ReactiveOAuth2AuthorizedClientManager authClientManager =
new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegs, authClientService);
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(authClientManager);
oauth.setDefaultOAuth2AuthorizedClient(true);
oauth.setDefaultClientRegistrationId("test");
return WebClient.builder()
.filter(oauth)
.build();
}
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ServerOAuth2AuthorizationRequestResolver resolver) {
http.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login(auth -> auth.authorizationRequestResolver(resolver));
return http.build();
}
#Bean
public ServerOAuth2AuthorizationRequestResolver pkceResolver(
ReactiveClientRegistrationRepository repo) {
DefaultServerOAuth2AuthorizationRequestResolver resolver =
new DefaultServerOAuth2AuthorizationRequestResolver(repo);
resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
return resolver;
}
}
The authorization works fine. When I open /showData in the browser, I'm redirected to the vendor's login page and when I come back, the requested data is displayed as it should be.
But the Scheduler is still blocked. I guess that has something to do with the Security Context which is linked only to the browser session, but I'm not so familiar with Spring Security to understand how to share the access (and refresh) token within the whole application.
Disclaimer: The Third-Party API has specific endpoints which are explicitly meant to be called periodically and not only on a user's request, but they still demand authorization by Authorization Code instead of Client Credential.
If you want to call third-party API from the scheduler you should pass OAuth2AuthorizedClient to it. That class represent an OAuth2 authorized client and has information about access/refresh token.
Here is the documentation describing how to use it.

hasAuthority() with Okta bearer token for Spring Cloud Gateway

I am having multiple downstream services to which I am routing via a spring cloud gateway service which also has okta auth. Currently I am able to route authenticate users at the gateway and return 401 for all requests without a valid bearer token. However when I try to implement role based auth, i.e. GET requests can be sent downstream for everyone group, but POST requests require 'admin' group membership in okta. This does not work as any authenticated user is currently able to make post requests. I have added claims to the access/id tokens and checked them in the Token preview section of my default Authorisation server in okta. Following is my security configuration.
#EnableWebSecurity
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests -> authorizeRequests
.antMatchers(HttpMethod.POST,"/*").hasAuthority("admin")
.anyRequest().authenticated())
.oauth2ResourceServer().jwt();
}
}
Due to only the gateway having okta auth and downstream services being protected by api token, I cannot implement preAuthorize and have to rely on httpsecurity, but I seem to be missing something

Spring Authorization Server: How to use login form hosted on a separate application?

I am using Spring Security along with Spring Authorization Server and experimenting with creating an auth server.
I have a basic flow allowing me to login with the pre-built login page (from a baledung guide - this is the code I'm working off ). I'm assuming this login page form comes from formLogin() like so:
http.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
//.formLogin(withDefaults());
return http.build();
I would like to not use this pre-built form as I have a need to host and run the login form front-end application completely separately. ie on a different server, domain and codebase.
Another way to ask this question could be:
How do I disable the built in form in authorization-server so I can use it with a completely separate form?
Are there any recommended ways of learning about how customise my SecurityFilterChain along these lines? Is this the correct place to look? I find the baledung article (and articles like that) helpful as a starting point, but seldom works for more practical use case. I'm confident Spring Security and the oauth2 libraries will allow me to do what I want, but not entirely clear.
After discussing this with you, I've gathered that what you're trying to do is essentially pre-authenticate the user that was authenticated through another (separately hosted) login page, actually a separate system. The idea is that the other system would redirect back with a signed JWT in a query parameter.
This really becomes more of a federated login problem at that point, which is what SAML 2.0 and OAuth 2.0 are aimed at solving. However, if you have to stick with things like a signed JWT (similar to a SAML assertion), we could model a fairly simple pre-authenticated authorization_code flow using the Spring Authorization Server.
Note: I haven't explored options for JWT Profile for OAuth 2.0 Client Authentication and Authorization Grants but it could be a viable alternative. See this issue (#59).
Additional note: There are numerous security considerations involved with the approach outlined below. What follows is a sketch of the approach. Additional considerations include CSRF protection, using Form Post Response Mode (similar to SAML 2.0) to protect the access token instead of a query parameter, aggressively expiring the access token (2 minutes or less), and others. In other words, using a federated login approach like SAML 2.0 or OAuth 2.0 will always be RECOMMENDED over this approach when possible.
You could to start with the existing Spring Authorization Server sample and evolve it from there.
Here's a variation that redirects to an external authentication provider and includes a pre-authentication mechanism on the redirect back:
#Bean
#Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
// #formatter:off
http
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("https://some-other-sso.example/login"))
);
// #formatter:on
return http.build();
}
#Bean
#Order(2)
public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
// #formatter:on
return http.build();
}
#Bean
public JwtDecoder jwtDecoder(PublicKey publicKey) {
return NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build();
}
#Bean
public BearerTokenResolver bearerTokenResolver() {
DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
bearerTokenResolver.setAllowUriQueryParameter(true);
return bearerTokenResolver;
}
The first filter chain operates on authorization server endpoints, such as /oauth2/authorize, /oauth2/token, etc. Note that the /oauth2/authorize endpoint requires an authenticated user to function, meaning that if the endpoint is invoked, the user has to be authenticated, or else the authentication entry point is invoked, which redirects to the external provider. Also note that there must be a trusted relationship between the two parties, since we're not using OAuth for the external SSO.
When a redirect from the oauth client comes to the /oauth2/authorize?... endpoint, the request is cached by Spring Security so it can be replayed later (see controller below).
The second filter chain authenticates a user with a signed JWT. It also includes a customized BearerTokenResolver which reads the JWT from a query parameter in the URL (?access_token=...).
The PublicKey injected into the JwtDecoder would be from the external SSO provider, so you can plug that in however it makes sense to in your setup.
We can create a stub authentication endpoint that converts the signed JWT into an authenticated session on the authorization server, like this:
#Controller
public class SsoController {
private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
#GetMapping("/login")
public void login(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
this.successHandler.onAuthenticationSuccess(request, response, authentication);
}
}
The .oauth2ResourceServer() DSL causes the user to be authenticated when the /login endpoint is invoked. It requires an access_token parameter (used by the BearerTokenResolver) to pre-authenticate the user by validating the signed JWT as an assertion that the user has been externally authenticated. At this point, a session is created that will authenticate all future requests by this browser.
The controller is then invoked, and simply redirects back to the real authorization endpoint using the SavedRequestAwareAuthenticationSuccessHandler, which will happily initiate the authorization_code flow.
Re your comnent: "I'm attempting to build an Authorization Server":
Coding your own Authorization Server (AS) or having to build its code yourself is highly inadvisable, since it is easy to get bogged down in plumbing or to make security mistakes.
By all means use Spring OAuth Security in your apps though. It is hard enough to get these working as desired, without taking on extra work.
SUGGESTED APPROACH
Choose a free AS and run it as a Docker Container, then connect to its endpoints from your apps.
If you need to customize logins, use a plugin model, write a small amount of code, then deploy a JAR file or two to the Docker container.
This will get you up and running very quickly. Also, since Spring Security is standards based, you are free to change your mind about providers, and defer decisions on the final one.
EXAMPLE IMPLEMENTATION
Curity, along with other good choices like Keycloak or Ory Hydra are Java based and support plugins:
Curity Community Edition
Custom Authenticator Example

Spring boot security, API-key protection OR oauth2 resourceServer for same resources

I have a spring boot 2.4 application where I want to protect it with either an API-key or a resource server. I was thinking that I could use filters here to first check if the api key is given and if so, grant access to the resource, otherwhise a "second chance" should be given to authenticate with an opaque oauth2-token (api key for machine to machine, token for frontend -> backend)
Where I get stuck is that my security config looks like this today (with a resource server activated)
#Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? =
http.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2ResourceServer {
it.authenticationManagerResolver(myMultiTenantResolver)
}
.build()
how would I go about to add an API-protection in here which should grant access (if it succeeds) without also invoking the resourceServer-snippet here (if it doesn't succeed, the resourceServer-snippet should be invoked)?
One possible solution can be as following:-
Create both your filters i.e the api-key filter and the auth-token filter.
In your configure(HttpSecurity http) method of ApplicationSecurityConfiguration add the api-key filter before the auth-token filter.
If you pass the api-key, put you authentication details in securityContextHolder. In the next filter(auth-token filter) Override the doFilter, where you need to check that if the previous filter has been authenticated, you do not run the current filter(auth-token filter) by calling chain.doFilter(request, response).
Please let me know if you need the complete implementation.

spring 5 - Oauth2 server get current user

I have build a Spring boot oauth2 server using spring 5. The oauth server works and I can login using basic auth and username/password. I get a bearer token and I can verify the token using the /oauth/check_token url.
In the same Spring boot project I want to add an endpoint that will print out the authenticated user information so that oauth2 clients can get information over the logged in user. I created an endpoint /user and it looks like this:
#GetMapping("/user")
#ResponseBody
public Principal user(Principal user) {
return user;
}
I startup postman so that I can do the api calls and such, call /oauth/token and I receive a token. I then start a new request, set the authentication method to bearer token and fill in the received bearer token. I do a GET call to the url (http://localhost:8080/user) and it turns out the principal is always null. I know because I can debug my application in Spring tool suite and Principal is always empty. I have also tried:
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)SecurityContextHolder.getContext() .getAuthentication();
That is empty as well. How can I create an endpoint that will print the user info so that clients can set the userInfoUri property.
I have the answer. I'll post it here just in case someone else runs into this problem.
I have a ResourceServerConfigurerAdapter with the following configure in it:
public void configure(HttpSecurity http) throws Exception {
http.anonymous()
.disable()
.requestMatchers()
.antMatchers("/api/user/**").and().authorizeRequests()
.antMatchers("/user").authenticated()
// More rules here
The reason it didn't work because of the first antMatchers("/api/user/**"). I changed it into this:
http.anonymous()
.disable()
.requestMatchers()
.antMatchers("**").and().authorizeRequests()
I believe that the first antMatchers determines the path in which it forces authorizeRequests (Enabling oauth2 security in that path) so if the first path is .antMatchers("/api/user/**") after that is .antMatchers("/user") then it won't match and the /user url won't have the oauth2 security enabled.

Resources