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

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.

Related

Default Login Form for Secured Methodes in Spring Security

Maybe I am thinking completely the wrong way. I want to use Spring Security for my web application and only secure some functions of my Controller class without specifying the URLs.
When I include the dependency spring-boot-starter-security everything is secured by default with a side default login form. So far so good.
Now I activate method security with #EnableGlobalMethodSecurity(securedEnabled = true) and mark some of my methods with #Secured("USER").
To have no security as default I define a custom SecurityFilterChain:
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll())
.build();
}
Of course I have a test user defined:
#Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("test")
.password("test")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
I get a 403 Forbidden on the secured methods. And a 404 Not Found when I add this to the SecurityFilterChain:
.formLogin((form) -> form
.loginPage("/login")
.permitAll()
Because the default login form is missing.
What do I need to do to get the default login form for the secured methods?
I want to use Spring Security for my web application and only secure some functions of my Controller class without specifying the URLs.
Spring Security's web support is URL-based, so this does seem to contradict it's purpose. You can use only method-based security, but all of the behavior you're missing is expected because the filter chain is not in play. See Spring Security filter chain and Method Security.
To have no security as default I define a custom SecurityFilterChain:
This would not be a best practice. Consider what happens when a developer forgets to add the #Secured or similar annotation. Defense in depth would be a better approach, which is why Spring Security requires every endpoint to be authenticated by default.
I get a 403 Forbidden on the secured methods. And a 404 Not Found when I add this to the SecurityFilterChain:
At the method level, the ExceptionTranslationFilter does not trigger the AuthenticationEntryPoint. This would explain why you don't get the default behavior of a redirect to /login.
When defining a custom login page with http.formLogin().loginPage("/login"), you are responsible for providing a login page. This would explain why you receive a 404 Not Found.
In order to get the default behavior, you need to specify something that causes requests to be processed appropriately by the filter chain prior to method security. For example, if all of your secured endpoints start with /secured, you should add that as an authorization rule:
http.authorizeHttpRequests((requests) -> requests
.mvcMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
);
But this still leaves a gap and does not practice defense in depth. So the best configuration would invert the rules and identify only URLs that should be allowed by default, such as static resources.
http.authorizeHttpRequests((requests) -> requests
.mvcMatchers("/static/**").permitAll()
.anyRequest().authenticated()
);
In either case, security exceptions would be thrown by the filter chain while processing requests to #Secured endpoints, and so the AuthenticationEntryPoint will be triggered. Keep in mind however that authentication and authorization are related but separate concepts. In Spring Security, it's the ExceptionTranslationFilter that is tying them together in a way that produces the expected user experience.

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

Handling token response in spring oauth2 client

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?

Protect specific resources id with OAuth2 on Spring Boot

I have a working OAUTH2 implementation on Spring Boot, with AuthorizationServer and ResourceServer on the same implementation, using password grant.
About the server:
The TokenStore is custom and uses a WebService to store the token remotely.
I have a custom AuthenticationProvider.
This works for controlling access to resources based on given authorities, for instance, in the ResourceServer config:
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/resource/**")
.hasAnyAuthority("USER", "ADMIN")
.antMatchers("/api/admin/**")
.hasAnyAuthority("ADMIN");
}
Now, I need to control that USER can access to "/api/resource/1" but not "/api/resource/2", this IDs can change and I fetch the list during the authentication.
I've tried to add the ID's list to OAuth2AccessToken additional information and adding a custom filter in the ResourceServer configuration but it always comes empty.
So, How's the proper way for implementing this without using JWT?
After some thinking and research, If someone is trying to achieve something similar, this is what I'll do:
Map the allowed ID's to authorities, e.g. ID_201 and the modules as roles, so I will have a ROLE_ADMIN.
It's possible to refer to path variables in Web Security Expressions, as explained in here. So the idea is to pass the variable (resource id) and check whether it's allowed or not.
public class WebSecurity {
public boolean checkResourceId(Authentication authentication, int id) {
//check if the list of authorities contains ID_{id}.
}
}
And in the Web Security config:
http
.authorizeRequests()
.antMatchers("/resource/{resourceId}/**").access("#webSecurity.checkResourceId(authentication,#resourceId)")
...
If you're working on Spring Boot with spring-security 4.0.4 be sure to upgrade to 4.1.1 as reported in this bug.

Spring boot security, applying an authentication filter only to certain routes

I'm building a web application which will contain an API and an admin interface in a single application. As a result, I need two types of authentication, token based auth for the API, and form based auth for the admin interface.
I've almost got it working by applying a filter to authenticate API tokens, however the filter is being executed for every request, and I only want it to be executes on paths matching '/api/**'.
Hopefully it's clear from my security configuration what I'm trying to do, but sadly it doesn't work as expected.
All API requests will start '/api/', while all admin interface requests will start '/admin/'. So I was hoping to apply different security rules to each.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/account/login").permitAll();
http.addFilterBefore(webServiceAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).authorizeRequests().antMatchers("/api/**").hasAuthority("APIUSER");
http.authorizeRequests().antMatchers("/admin/**").authenticated().and()
.formLogin()
.loginPage("/admin/account/login").permitAll()
.passwordParameter("password")
.usernameParameter("username")
.failureUrl("/admin/account/login?error").permitAll()
.defaultSuccessUrl("/admin/dashboard")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/account/logout"))
.logoutSuccessUrl("/admin/account/login");
http.exceptionHandling().accessDeniedPage("/admin/account/forbidden");
}
There is a way to configure several HttpSecuritys depending on the url by using the antMatcher (or in more advanced cases requestMatchers) on the HttpSecurity directly (not on authorizeRequests!). See: https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#antMatcher-java.lang.String-
This requires defining several WebSecurityConfigurerAdapters with defined #Orders such that Spring uses the first appropriate configuration depending on the given url and the order of the configurations. For more details please take a look at the docs at http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
I don't know if this is the 'correct' way of doing it, but I've managed to only get the filters code to execute when a route is matched with '/api/**' by adding an if statement to the filter itself;
So within my filter I have the following;
AntPathMatcher urlMatch = new AntPathMatcher();
if (urlMatch.match("/api/**", httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()))) {
// Token authentication in here
}

Resources