@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public TokenAuthenticationTokenFilter getTokenFiter(){
return new TokenAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(getTokenFiter(), UsernamePasswordAuthenticationFilter.class);
http
.authorizeRequests()
.antMatchers("/Login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable();
}
}
public class TokenAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private RedisUtils redisUtils;
public TokenAuthenticationTokenFilter(){
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("token");
if(!StringUtils.hasText(token)){
filterChain.doFilter(request,response);
return;
}
Object o =redisUtils.get(token);
if (o==null){
response.setStatus(200);
response.setCharacterEncoding("utf-8");
response.getWriter().write(JSON.toJSONString(Result.failed(401,"token 非法","")));
return;
}
Map<String,String> maps=new HashMap<>();
Map Values = JSON.parseObject(o.toString(), maps.getClass());
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(Values.get("role").toString()));
UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(new Userdto(), null, authorities);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request,response);
}
}