1.在pom.xml文件中导入依赖
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
2.创建一个配置文件继承 WebSecurityConfigurerAdapter 并开启注解@EnableWebSecurity
3.快捷键 ALT+Ins 选择重写方法,重写 configure(HttpSecurity http)方法
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
}
4.设置请求授权的规则
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {
/** 授权 */
@Override
protected void configure(HttpSecurity http) throws Exception {
/** 首页请求所有人都能访问 permitAll() */
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
/** 没有权限默认会到登录页面,需要开启登录页面 */
/** .loginPage("/toLogin")跳转页面自定义 */
//.usernameParameter() 自定义用户参数
//.passwordParameter()
http.formLogin().loginPage("/toLogin");
/** 开启注销功能 */
// 拦截/loginout请求后发出"/"请求跳转到指定页面/"
http.logout().logoutSuccessUrl("/");
/** 开启记住我功能 */
http.rememberMe();
}
/** 认证 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("fengfeng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
5.导入thymeleaf和security的整合依赖(maven中心仓库)
6.实现根据权限显示模块thymeleaf头部命名空间
xmlns:th=http://www.thymeleaf.org
xmlns:sec=http://www.thymeleaf.org/extras/spring-security
xmlns:shiro=http://www.pollix.at/thymeleaf/shiro
html lang=en xmlns:th=http://www.thymeleaf.org
xmlns:sec=http://www.thymeleaf.org/extras/spring-security
xmlns:shiro=http://www.pollix.at/thymeleaf/shiro
sec:authorize="hasRole("xxx") //按照权限显示
sec:authorize="!isAuthenticated()" //是否登录显示