SpringBootSecurity(二)token认证

338 阅读1分钟
  • token 过滤器
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (Strings.isEmpty(token)) {
            filterChain.doFilter(request,response); // 放行
            return;
        }
        // 验证token
        String userId = TokenUtil.getUserIDByToken(token);
        if (Strings.isEmpty(userId)) {
            filterChain.doFilter(request,response); // 放行
            return;
        }
        // 存入 SecurityContextHolder
        User user = userMapper.selectById(Long.valueOf(userId));
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setToken(token);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
  • 配置
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private AuthenticationTokenFilter authenticationTokenFilter;

    // 配置加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置认证
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    // 配置过滤
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable() // 关闭 csrf
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 关闭session 验证
                .and()
                .authorizeHttpRequests()
                .antMatchers("/api/login").permitAll()
                .anyRequest().authenticated();
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }

}
  • Controller 测试
@RestController
@RequestMapping("/api/test")
public class TestController {

    @GetMapping("/hello")
    public String index() {
        return "学习Security";
    }

}