Home > database >  Combine JWT authentication and authorizeRequests
Combine JWT authentication and authorizeRequests

Time:03-22

I am building a spring boot API for security I use JWT token, I also developed a web version for authentication I use authorizeRequests.

I want to combine the two authentication modes so that the filter is used for all URLs that start with /api/** and requestMatchers are applied for the rest.

This works perfectly for the webClient application:

http.authorizeRequests().antMatchers("/h2-console/**").permitAll().and().formLogin().loginPage("/login");

And it works correctly for the API :

http.csrf().disable()
            .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/signin").permitAll()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated();

""

Can you please help to conbine the two codes

Thank you in advance

CodePudding user response:

We can configure multiple HttpSecurity instances just as we can have multiple http blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times.

CodePudding user response:

I used multiple HttpSecurity and it works perfectely thank you for you help

@EnableWebSecurity
@Order(1)
@Configuration
public static class RestConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/api/**")
            .cors()
                .and()
            .csrf()
                .disable() // we don't need CSRF because our token is invulnerable
            .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/signin").permitAll()
                .antMatchers(HttpMethod.POST, "/api/signup").permitAll()
                .antMatchers("/api/signin").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}


    
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.authorizeRequests().antMatchers("/h2-console/**").permitAll().and().formLogin().loginPage("/login");
    }
}
  • Related