引入pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
设置Spring Security的配置类
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class securityConfigTest extends WebSecurityConfigurerAdapter {
//注入UserDetailsService类对象用于密码的校验
@Autowired
private UserDetailsService userDetailsService;
//注入数据源操作数据库
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
// jdbcTokenRepository.setCreateTableOnStartup(true); 让Spring Security帮我们创建自动登录的记录表
return jdbcTokenRepository;
}
//配置类继承后重写的方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(password());//调用我们设置的验证规则,和密码的加密方式
}
@Bean
public PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//登出后跳转页面
http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").permitAll();
//没有权限后的跳转页面403
http.exceptionHandling().accessDeniedPage("/unauth.html");
//对于表单登录的跳转规则设置
http.formLogin()
.loginPage("/login.html")//未登录跳转到登录页面
.loginProcessingUrl("/user/login")//Spring Security定义的登录接口
.defaultSuccessUrl("/success.html").permitAll()//登陆成功之后跳转的路径
.and().authorizeRequests()//请求授权
.antMatchers("/","/test/hello","/user/login").permitAll()//对这些请求进行放行,一定要把登录成功后跳转的接口放行不然会死循环
// .antMatchers("/test/index").hasAuthority("admin")
// .antMatchers("test/index").hasAnyAuthority("admin,root")
.antMatchers("/test/index").hasRole("sale")//为相应的路径分配权限,具有权限或者角色的就放行
.anyRequest().authenticated()
.and().rememberMe().tokenRepository(persistentTokenRepository())//自动登录的token验证
.tokenValiditySeconds(60)//设置时长单位秒
.userDetailsService(userDetailsService)
.and().csrf().disable();
}
}
注解方式:
在配置类上加:
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
注解示例:
// @Secured({"ROLE_sale","ROLE_manager"})
@PreAuthorize("hasAnyAuthority('admin')")
public String update (){
return "update!!!";
}