jwt和spring security集成

 

 

1、用户登陆,通过spring security验证用户(WebSecurityConfigurerAdapter的configure(AuthenticationManagerBuilder)方法),并且进行授权(WebSecurityConfigurerAdapter的configure(HttpSecurity))。并且根据拦截器,不需要对其验证token。

验证:

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            // 设置 UserDetailsService
            .userDetailsService(userDetailsService)
            // 使用 BCrypt 进行密码的 hash
            .passwordEncoder(passwordEncoder());
}    

 授权:

public void configure(HttpSecurity http) throws Exception {

  http
  // Un-secure 登录、 验证码接口,不用授权就可以无条件访问,也就是所有人都可以访问登陆接口 .antMatchers( "/api/auth/**", "/alogin" ).permitAll() //无条件允许访问 // secure other api .anyRequest().authenticated();
}

 

2、验证通过后,需要通过Jwt功能,生成token,并将token返回给客户端,客户端将token保存在cookie或者localstorage中

//生成token
String token = jwtUtils.generateToken(userId);

 

3、客户登陆成功后再次访问服务,携带在token(将其放在请求头Authorization字段中),请求服务端。

4、 由于登陆成功后,再次请求服务端,是通过携带token通过jwt验证,而不是通过用户名密码的形式通过spring security验证,所以需要通过自定义过滤器,验证token是否正确


public void configure(HttpSecurity http) throws Exception {

//
将token验证添加在用户名密码验证前面,authenticationTokenFilterBean()方法返回了自定义的过滤器,用来验证token是否正确
//其实这部分是验证的内容,但是写在了httpSecurity授权中,为什么这么设计
httpSecurity .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}

 

说明:

HttpSecurity 的addFilterBefore方法:

addFilterBefore

public HttpSecurity addFilterBefore(javax.servlet.Filter filter,
                                    java.lang.Class<? extends javax.servlet.Filter> beforeFilter)
Description copied from interface: HttpSecurityBuilder
Allows adding a Filter before one of the known Filter classes. The known Filter instances are either a Filter listed in HttpSecurityBuilder.addFilter(Filter) or a Filter that has already been added using HttpSecurityBuilder.addFilterAfter(Filter, Class) or HttpSecurityBuilder.addFilterBefore(Filter, Class).
Specified by:
addFilterBefore in interface HttpSecurityBuilder<HttpSecurity>
Parameters:
filter - the Filter to register before the type beforeFilter
beforeFilter - the Class of the known Filter.
Returns:
the HttpSecurity for further customizations

 

 

tips:

如果携带了token,则进行token验证,也就是要通过自定义的过滤器;如果没有携带token,则不进行token验证,直接用UsernamePasswordAuthenticationFilter类,通过用户名密码的形式进行验证。

 

自定义过滤器设计思路:

所以自定义过滤器的逻辑应该是判断token是否存在,如果存在则进行token验证,如果不存在则不需要过滤。

 

posted @ 2019-07-09 10:41  第二人生Bonnie  阅读(811)  评论(0编辑  收藏  举报