一、原理
二、实现
以下为jdbc实现案例
1.创建数据库表
2.在配置类中配置数据源
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); 自动配置数据表
return jdbcTokenRepository;
}
3.配置类方法中配置自动登录
.and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60)//设置有效时长,单位秒
.userDetailsService(userDetailsService)
配置类整体如下
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private DataSource dataSource;
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); 自动配置数据表
return jdbcTokenRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(password());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedPage("/error.html");//配置没有权限访问跳转的自定义页面
http.logout().logoutUrl("/logout").logoutSuccessUrl("/index").permitAll();//用户注销
http.formLogin() //自定义编写的登录页面
.loginPage("/login.html")//登录页面设置
.loginProcessingUrl("/user/login")//登录后访问路径
.defaultSuccessUrl("/test/index")//登录成功后跳转路径
.and().authorizeRequests()
.antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
.antMatchers("/test/index").hasAnyRole("sale,master")//具有ROLE_sale,ROLE_master的角色可以访问这个路径
.anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
.and().rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60)//设置有效时长,单位秒
.userDetailsService(userDetailsService)
.and().csrf().disable();//关闭csrf防护
}
@Bean
PasswordEncoder password()
{
return new BCryptPasswordEncoder();
}
}