上篇文章主要是做了准备工作,这篇将介绍SpringBoot security和Jwt的结合
SpringBoot security相关代码说明
从上篇文章中提到的WebSecurityConfig讲起,下面的configure方法主要是添加了http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
,使得所有请求都将经过Jwt过滤器,Jwt过滤器负责验证用户身份并把用户角色列表传递给Security框架管理。
@Override
protected void configure(HttpSecurity http) throws Exception {
// Disable CSRF (cross site request forgery)
http.csrf().disable();
// No session will be created or used by spring security
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Entry points
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll() //配合@CrossOrigin 解决跨域问题
.antMatchers("/users/signin").permitAll()//开放登录
.antMatchers("/users/signup").permitAll()//开发注册
.antMatchers("/test/**").permitAll() // test/**无需websecurity认证
// Disallow everything else..
.anyRequest().authenticated(); // 其他请求都需要认证
// 所有请求都将被JwtTokenFilterConfigurer拦截
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
}
Jwt相关代码说明
在JwtTokenFilterConfigurer中,会执行JwtTokenFilter过滤器。JwtTokenFilter过滤器主要代码如下:
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = jwtTokenProvider.resolveToken(httpServletRequest);
try {
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication auth = jwtTokenProvider.getAuthentication(token);
// 传值给controller,controller可使用@PreAuthorize注解进行认证
SecurityContextHolder.ge