package com.panzhihua.auth.config; import javax.annotation.Resource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.panzhihua.auth.handel.AjaxAuthenticationEntryPoint; import com.panzhihua.auth.handel.UserAuthenticationProvider; import com.panzhihua.auth.handel.UserLoginFailureHandler; import com.panzhihua.auth.handel.UserLogoutSuccessHandler; /** * SpringSecurity配置类 * * @Author youcong */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 自定义登录逻辑验证器 */ @Resource private UserAuthenticationProvider userAuthenticationProvider; public static void main(String[] args) { BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); String encode = bCryptPasswordEncoder.encode("123456"); System.out.println(encode); } /** * 加密方式 * * @Author youcong */ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } /** * 配置登录验证逻辑 */ @Override protected void configure(AuthenticationManagerBuilder auth) { // 这里可启用我们自己的登陆验证逻辑 auth.authenticationProvider(userAuthenticationProvider); } /** * 解决 无法直接注入 AuthenticationManager * * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 配置security的控制逻辑 * * @Author youcong * @Param http 请求 */ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().permitAll().and() // 配置登录成功自定义处理类 .formLogin() // .successHandler(new UserLoginSuccessHandler()) // 配置登录失败自定义处理类 .failureHandler(new UserLoginFailureHandler()).and() // 配置登出地址 .logout().logoutUrl("/login/userLogout") // 配置用户登出自定义处理类 .logoutSuccessHandler(new UserLogoutSuccessHandler()).and() // 开启跨域 .cors() // 异常处理(权限拒绝、登录失效等) .and().exceptionHandling().authenticationEntryPoint(new AjaxAuthenticationEntryPoint())// 匿名用户访问无权限资源时的异常处理; .and() // 取消跨站请求伪造防护 .csrf().disable(); // 基于Token不需要session http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用缓存 http.headers().cacheControl(); } }