PermitAll with addFilterAfter not working - spring-security

Struggling with new Spring Security 6.x. Having the following SecuritsFilterChain:
#Configuration
#EnableWebSecurity
#EnableMethodSecurity
public class SecurityConfiguration {
public SecurityConfiguration() {}
#Bean
#Order(1)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/swagger-ui/**", "/swagger-ui/index.html**", "/swagger-ui/index.html/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterAfter(new JWTAuthorizationFilter(), BasicAuthenticationFilter.class));
return http.build();
}
Unfortunately the URL:
/swagger-ui/index.html
executes the filter JWTAuthorizationFilter which should not be executed.
Without the filter it works.

First, allow me to suggest a few changes for readability, and then I'll comment after that:
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(...).permitAll()
.anyRequest().authenticated()
)
.addFilterAfter(new JWTAuthorizationFilter(), BasicAuthenticationFilter.class)
return http.build();
}
The nice thing about this is that it's a little easier to see the authorization rules separately from the rest of the filters being configured.
permitAll
Authentication filters are called on every request.
permitAll(), authenticated(), and hasRole() all work with AuthorizationFilter, which is placed after the authentication filters in the filter chain.
What this means is that JWTAuthorizationFilter, BasicAuthenticationFilter, and all authentication filters are not affected by any authorization rules that you add.
If there are certain requests that JWTAuthorizationFilter should skip, that is up to that filter to say so.

Related

Getting unauthorized after login in spring boot reactive

I'm trying to create form login with spring boot webflux. I can login and after login I'm redirectored successfully. But when I browse to a page that requires authentication, I'm getting error. If I remove the page from security config and get principal from ReactiveSecurityContextHolder I'm getting the user details.
Here is my security config:
public class SecurityConfig {
#Autowired
private UserService userService;
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"))
.authenticationManager(reactiveAuthenticationManager())
.and()
.logout()
.and()
.build();
}
#Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null));
}
}
Do I need to do anything else in the ReactiveAuthenticationManager? Is that even required?
In this repository : https://github.com/mohamedanouarbencheikh/dashboard-auth-microservice
you have a complete example of spring security implementation with jwt in microservice architecture using spring cloud routing (gateway) which is based on reactive programming and Netty as application server, and angular as frontend
Answering to my own question so that anyone facing same problem can get some help:
The issue was resolved when I've changed the UsernamePasswordAuthenticationToken constructor and passed the authority parameter as null. This is really ridiculous. Here is the updated code:
#Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()));
}
I've also simplified the config by removing authenticationSuccessHandler and authenticationManager from the config. Spring automatically redirects to /. For authenticationManager it automatically checks for a ReactiveAuthenticationManager bean and uses if found. Here is my updated config:
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.and()
.logout()
.logoutUrl("/user/logout")
.logoutSuccessHandler(logoutSuccessHandler("/user/bye"))
.and()
.build();
}

Oauth2Login for only specific urls

I'm trying to have an oauth2 configuration setup for login through Spring Security. But only for specific urls.
My security config looks as follows.
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secured/**")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService());
}
Basically I only want the oauth2Login to be trigger for urls that start with /secured. It seems to almost work, the only issue is whenever Spring trys to re-direct my session to google for authentication it triggers a 404.
The standard redirect for an oauth authentication should fire off to http://localhost:8080/oauth2/authorization/google, which my application attempts to do, but it 404's.
I'm assuming the http://localhost:8080/oauth2/authorization/google url is being blocked by some type of security config? But I cannot for the life of me figure out why.
I'm guessing I need to find the right combination of .permitAll() for any request going to "/oauth2/authorization/**"
I've tried this below.
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secured/**")
.authorizeRequests()
.antMatchers("/oauth2/authorization/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService());
}
But that won't work.....does anyone see my issue? I have no other security config conflicting with this one, I'm at a bit of a loss.
According to previous answer, the version with no lambda-style should look like this right?
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests
.antMatchers("/secured/**").authenticated()
.anyRequest().authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService());
}
If we want oauth2Login only for "/secured/**", why have we to use authenticated() for antMatcher("/secured/**") and for anyRequest() (and not permitAll() for anyRequest())?
Thank you.
The first step to understanding the issue here is understanding the difference between http.antMatcher() and http.authorizeRequests().
Let's look at the following configuration.
(I am using the lambda-style configuration, available as of Spring Security 5.2, to make it more readable)
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secured/**")
.authorizeRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2Login(oauth2Login -> oauth2Login
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService())
);
}
Here, we are specifying that HTTP security will only be invoked when matching "/secured/**".
In other words, the request will only be processed by the SecurityFilterChain if it matches "/secured/**".
This is a problem because the SecurityFilterChain is what initiates the Authorization Request from "/oauth2/authorization/google".
However, the SecurityFilterChain is not called because "/oauth2/authorization/google" does not match "/secured/**".
Consider the following configuration instead.
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.antMatchers("/secured/**").authenticated()
.anyRequest().permitAll()
)
.oauth2Login(oauth2Login -> oauth2Login
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService())
);
}
Here, the HTTP security will be invoked for all requests.
However, only requests that match "/secured/**" will require the user to authenticate.
The answer of #eleftheria-stein-kousathana brought me to another possible solution.
As stated it is important to know that the OAuth Endpoints won't called because the security config for them is bound to the antMatcher() call directly following the HttpSecurity object.
But as stated in the docs you can also change the baseUris of the redirectionEndpoint and the authorizationEndpoint
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/secured/**")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
//New Code Starting here
.authorizationEndpoint()
.baseUri("/secured/oauth2/authorization")
.and()
.redirectionEndpoint()
.baseUri("/secured/oauth2/code/*")
.and()
//new code ending here
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(authorizedClientService());
}
Be sure to change the redirectUriTemplate of your clientRegistration and also the redirect uri configured at your AuthorizationServer
AND be sure to add the asterisk at the end of the redirectionEndpoint.baseUri ... that cost me some minutes to figure out what was wrong :-)

where i should properly store first password

I have a question about storing "base" password for spring security app. I read documentation and IMHO i should have first pass stored somewhere hardcoded. Is that right or how i should be done?
As example i've post defauld helloWorld code from spring security.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Bean
#Override
public UserDetailsService userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String s = encoder.encode("password");
UserDetails user = User.withUsername("userName")
.password(s)
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
You have several options.
Hardcode it.
Store username/pass in a .property file. This gives you more flexibility, and also an ability to disable the user (e.g. set the name to empty and skipping it in the code)
Generate password via existing PasswordGenerator and add login/pass manually to a DB via SQL. This way you have even more flexibility, you can have as many initial users as you want (and you can always delete them), and also this approach can guarantee that logins will be unique (you need some special handling in your code to check, that the login of any new user doesn't match the login of the first user).

Spring Security exclude URL on custom filter

#SuppressWarnings("SpringJavaAutowiringInspection")
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder
authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService);
}
#Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/test").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
I have a custom filter that runs before Spring Security. I want to be able to exclude some URLs (like /test) from the filter and Spring Security and others to be intercepted (like /api/**).
When using postman to test localhost/test it still goes through the filter even though I have antMatchers("/test").permitAll().
How do I bypass the filter?
You can disable the Spring Security filter chain for some URLs, see WebSecurity#ignoring:
Allows adding RequestMatcher instances that should that Spring Security should ignore. Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.
Example Usage:
webSecurityBuilder.ignoring()
// ignore all URLs that start with /resources/ or /static/
.antMatchers("/resources/**", "/static/**");
Therefore, you can override WebSecurityConfigurerAdapter#configure:
Override this method to configure WebSecurity. For example, if you wish to ignore certain requests.
To ignore path /test you have to add following method to your configuration:
public void configure​(WebSecurity web)
webSecurityBuilder
.ignoring()
.antMatchers("/test");
}

How to override the Spring Boot default OAuthTokenEndpoint

I've been working on securing a Restful Service using Spring Security Oauth. I've been banging my head trying to secure the /oauth/token endpoint using SSL and only allowing for POST calls.
I'm using #EnableAuthorizationServer which states
Convenience annotation for enabling an Authorization Server (i.e. an
AuthorizationEndpoint and a TokenEndpoint) in the current application
context, which must be a DispatcherServlet context. Many features of
the server can be customized using #Beans of type
AuthorizationServerConfigurer (e.g. by extending
AuthorizationServerConfigurerAdapter). The user is responsible for
securing the Authorization Endpoint (/oauth/authorize) using normal
Spring Security features (#EnableWebSecurity etc.), but the Token
Endpoint (/oauth/token) will be automatically secured using HTTP Basic
authentication on the client's credentials. Clients must be registered
by providing a ClientDetailsService through one or more
AuthorizationServerConfigurers.
Which is great, but I can't seem to override the token endpoint piece or enforce POST-only calls, like with the intercept-url xml syntax
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore()
}
#Autowired
AuthenticationManager authenticationManager
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient('testApp')
.scopes("read", "write")
.authorities('ROLE_CLIENT')
.authorizedGrantTypes("password","refresh_token")
.secret('secret')
.accessTokenValiditySeconds(7200)
}
}
I secured my Resource server with
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Autowired
private RestAuthenticationEntryPoint authenticationEntryPoint;
#Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.requiresChannel().anyRequest().requiresSecure()
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
}
}
Is there a similar builder syntax for the Authorization Servers TokenEndpoint security that uses requiresChannel?
I ended up creating my own config using
org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration
Since i'm using Spring boot I just autowired the SecurityProperties and added this line for the SSL on the Oauth endpoints
if (this.security.isRequireSsl()) {
http.requiresChannel().anyRequest().requiresSecure();
}
And for the POST requirement
http
.authorizeRequests()
.antMatchers(HttpMethod.POST,tokenEndpointPath).fullyAuthenticated()
.antMatchers(HttpMethod.GET,tokenEndpointPath).denyAll()
Afterwards removed the #EnableAuthorizationServer so it would use my config.

Resources