一:导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二:添加配置文件
在配置文件上添加@EnableWebSecurity 注解,并使得该类继承 WebSecurityConfigurerAdapter 通过重写configure方法即可进行安全配置
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()// 所有人可以访问
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有权限会默认跳转到登录页面
// http.formLogin(); //要是不设置自己的登录页,就直接跳转到自带的登录页面
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");// 开启登陆的页面
http.logout().logoutSuccessUrl("/");// 开启了注销
http.exceptionHandling().accessDeniedPage("/403");//设置没有权限时显示的页面
http.rememberMe();// 开启记住我功能
http.csrf().disable();//关闭
}
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置认证信息
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("geng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3");
// jdbc数据
// auth.jdbcAuthentication().dataSource().usersByUsernameQuery("").authoritiesByUsernameQuery();
// 通用用户 ---需要实现自定义的UserDetailsService接口
// auth.userDetailsService(userDetailsService);
}
}
三:当使用的是mybatis框架来进行数据库查询用户时,可以简单的实现UserDetailService接口,并重写里面的 loadUserByUsername(String username)方法,在方法中根据传入的username在数据库中查找该用户的信息,并将信息封装到SpringSecurity的User中,并给与其权限代码如下:
public class CustomUserDetailsServce implements UserDetailsService {
@Autowired
UsersMapper usersMapper; //dao层
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 根据username查询数据库中的users信息
Users users = usersMapper.queryUserByUsername(username);
// 简单的给该用户授权,一般都是根据数据库查询到的权限授权,此处没有查询数据库,就是自定义
List<GrantedAuthority> authorities=new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_vip1"));
// 返回springsecurity包装的user对象
return new User(users.getUsername(),users.getPassword(),authorities);
}
修改SecurityConfig 中的认证不符的代码,注意要设置密码的加密方式
@Bean
UserDetailsService customUserDetailsServce(){
return new CustomUserDetailsServce();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
auth.userDetailsService(customUserDetailsServce()).passwordEncoder(new BCryptPasswordEncoder());
}
四:可以在页面上使用,要引入:
xmlns:th="http://www.thymeleaf.org"