一.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二.添加配置类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAccessDecisionManager accessDecisionManager;
@Autowired
private CustomFilterInvocationSecurityMetadataSource securityMetadataSource;
@Autowired
private AuthenticationAccessDeniedHandler accessDeniedHandler;
@Autowired
private AuthFailHandler authFailHandler;
@Autowired
private AuthSucHandler authSucHandler;
@Autowired
private HrService hrService;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(hrService).passwordEncoder(passwordEncoder());
}
/**
* 配置需要忽略的路径
* @param webSecurity
* @throws Exception
*/
@Override
public void configure(WebSecurity webSecurity) throws Exception{
webSecurity.ignoring().antMatchers("/index.html","/static/**","/login_p");
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setAccessDecisionManager(accessDecisionManager);
object.setSecurityMetadataSource(securityMetadataSource);
return object;
}
})
.and()
.formLogin().loginProcessingUrl("/login")
.failureHandler(authFailHandler)
.successHandler(authSucHandler)
.permitAll()
.and()
.logout().permitAll()
.and().csrf().disable()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
}
-
@EnableGlobalMethodSecurity(prePostEnabled = true) 开启方法安全校验
-
PasswordEncoder用于设置加密方式
-
protected void configure(AuthenticationManagerBuilder auth); 指定登陆用户信息的获取方式,这里使用数据库方式获取,获取方法根据hrservice定义,该类实现UserDetailsService并重写了loadUserByUsername
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Hr hr = getHrByUsername(username); if(hr == null){ throw new UsernameNotFoundException("用户名不存在"); } return hr; }
-
public void configure(WebSecurity webSecurity) ;用于配置忽略的连接后缀
-
protected void configure(HttpSecurity httpSecurity);用于设置权限校验的方式,这里引入了自定义的CustomFilterInvocationSecurityMetadataSource用于获取请求url锁具有的权限。引入CustomAccessDecisionManager用于对用户权限进行校验。引入AuthenticationAccessDeniedHandler用于登录拒绝的处理,AuthFailHandler用于登录失败的处理,AuthSucHandler用于登录成功