简体   繁体   中英

Spring Security with JWT

I am trying to develop Spring Security project with JWT. I want access Login api with out Spring Security (without JWT token). But with below configuration, every time (for login api as well) it is checking for JWT token giving me 403 error.

Below is my WebSecurityConfig.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtAuthFilter jwtAuthFilter;

@Autowired
private TokenAuthenticationService jwtAuthenticationProvider;

@Override
public void configure(AuthenticationManagerBuilder auth)  throws Exception {
    auth.authenticationProvider(jwtAuthenticationProvider);
}



@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().ignoringAntMatchers("/api/v1/login");
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/api/v1/login")
            .permitAll()
            .and()
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
}

}

Thanks in advance

For login path configuration something like this can be used:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
            .usernameParameter("username") // default is username
            .passwordParameter("password") // default is password
            .loginPage("/authentication/login") // default is /login with an HTTP get
            .failureUrl("/authentication/login?failed") // default is /login?error
            .loginProcessingUrl("/authentication/login/process"); // default is /login
                                                                    // with an HTTP
                                                                    // post
}

If some paths need to be ignored configure(WebSecurity web) can be overridden:

@Override
public void configure(WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/api/v1/somepath").antMatchers("/static/**");
}

There is filter class named JwtAuthFilter that is being executed before every service you call.

.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) 

this code provides to be executed filter before every request, but its okay, you have to see this FilterClass there must be some check if token doesnt exist filter class must be returned and request will directly go to the login service. if you can show that Filter class and I will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM