springboot|整合springboot+springsecurity+thymeleaf

1.导入依赖

org.thymeleaf.extras thymeleaf-extras-springsecurity4 3.0.4.RELEASE org.springframework.boot spring-boot-starter-security org.thymeleaf thymeleaf-spring5 3.0.11.RELEASE >compile org.thymeleaf.extras thymeleaf-extras-java8time 3.0.4.RELEASE >compile org.springframework.boot spring-boot-starter-web

2.配置文件,关闭thymeleaf的缓存
spring: thymeleaf: cache: false

3.配置security的授权和认证规则
//springSecurity配置类 //AOP:拦截器 @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() .loginPage("/toLogin") .loginProcessingUrl("/login") .usernameParameter("username") .passwordParameter("password"); //注销,跳转到首页 http.logout().logoutSuccessUrl("/index"); http.csrf().disable(); //关闭csrf功能//开启记住我 http.rememberMe().rememberMeParameter("remember"); }//认证 //密码编码PassWordEncoder //在spring security5.0+ 新增了很多加密方法 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //从内存中加载用户,代替从数据库中查询 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("kuang").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3") .and() .withUser("test").password(new BCryptPasswordEncoder().encode("123")).roles("vip3"); } }

4.配置thymeleaf 头部引入约束
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

在div里添加属性
sec:authorize="isAuthenticated()"
已经认证的账号的会显示该div中的内容

在div里添加属性
sec:authorize="hasRole('vip1')"
有vip1权限的用户会显示div中内容

5.下面是index.html全文
首页 :src="https://www.it610.com/article/@{/qinjiang/js/jquery-3.1.1.min.js}"> :src="https://www.it610.com/article/@{/qinjiang/js/semantic.min.js}">

    推荐阅读