@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private UserMapper userMapper;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("token");
if (Strings.isEmpty(token)) {
filterChain.doFilter(request,response);
return;
}
String userId = TokenUtil.getUserIDByToken(token);
if (Strings.isEmpty(userId)) {
filterChain.doFilter(request,response);
return;
}
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()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.antMatchers("/api/login").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
}
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/hello")
public String index() {
return "学习Security";
}
}