Spring Boot中使用JWT及拦截器配置以及各层次的介绍
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.example.demo.security.jwt.JwtAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 其他配置 ...
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
// 其他配置 ...
}
}
这段代码定义了一个SecurityConfig
类,继承自WebSecurityConfigurerAdapter
。它创建了一个JwtAuthenticationFilter
的Bean,并在configure
方法中将其添加到Spring Security的过滤器链中,并指定它在UsernamePasswordAuthenticationFilter
之前。这样配置后,JWT认证过滤器会在用户名密码认证过滤器之前执行,用于处理和验证JWT token。
评论已关闭