在springsecurity的核心配置类可以配置的东西特别多,比如下面最常见的:
1.配置用户名和密码
2.配置登录界面,登录提交的路径,登录成功的路径
3.配置认证出现异常的路径
4.配置退出路径,退出成功路径
5.配置哪些路径是可直接访问和需要认证访问的
6.配置认证成功后,需要哪些权限或者角色才能访问的
7.可配置【记住我】功能
8.配置CSRF
9.配置未授权的统一处理类
10.配置退出处理器
11.配置认证过滤器 和 授权过滤器
参考代码如下:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; private TokenManager tokenManager; private DefaultPasswordEncoder defaultPasswordEncoder; private RedisTemplate redisTemplate; @Autowired public TokenWebSecurityConfig(UserDetailsService userDetailsService, DefaultPasswordEncoder defaultPasswordEncoder, TokenManager tokenManager, RedisTemplate redisTemplate) { this.userDetailsService = userDetailsService; this.defaultPasswordEncoder = defaultPasswordEncoder; this.tokenManager = tokenManager; this.redisTemplate = redisTemplate; } /** * 配置设置 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(new UnauthorizedEntryPoint()) //配置未授权统一处理类 .and().csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and().logout().logoutUrl("/admin/acl/index/logout") .addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate)).and() //配置退出处理器 .addFilter(new TokenLoginFilter(authenticationManager(), tokenManager, redisTemplate)) //配置认证过滤器 .addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager, redisTemplate)).httpBasic(); //配置授权过滤器 } /** * 密码处理 * @param auth * @throws Exception */ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder); } /** * 配置哪些请求不拦截 * @param web * @throws Exception */ @Override public void configure(WebSecurity web) throws Exception { // web.ignoring().antMatchers("/api/**", // "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**" // ); web.ignoring().antMatchers("/*/**" ); } }