SpringBoot:thymeleaf整合SpringSecurity

  • 引入整合包
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
  • 自定义SpringSecurity配置类
/**
 * SpringSecurity配置类
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 定义授权规则
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可访问,功能也对应有权限的人才可以访问[链式编程]
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/l1/**").hasRole("vip1")
                .antMatchers("/l2/**").hasRole("vip2")
                .antMatchers("/l3/**").hasRole("vip3");
        //没有权限默认会到登录页,需要开启登录的页面
        http.formLogin();
        //开启注销功能,注销成功会重定向到主页面
        http.logout().logoutSuccessUrl("/");
        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    /**
     * Auth定义认证规则
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * JDBC认证:auth.jdbcAuthentication()
         * 内存认证:auth.inMemoryAuthentication()
         */
        //在SpringBoot 2.1.x版本之上,会有PasswordEncoder这个错误
        //PasswordEncoder:密码编码[加密]
        //SpringSecurity 5.0+增加了很多的加密方法
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zs").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
    }
}
  • 引入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4
  • 判断是否认证、获取用户角色和判断是否拥有角色
<!--判断认证-->
<!--未认证-->
<div sec:authorize="!isAuthenticated()">显示未认证内容</div>
<!--已认证-->
<div sec:authorize="isAuthenticated()">显示认证内容</div>

<!--获取用户和角色-->
<!--获取用户-->
<span sec:authentication="name"></span>
<!--获取角色-->
<span sec:authentication="principal.authorities"></span>

<!--判断是否拥有角色-->
<div sec:authorize="hasRole('VIP1')"></div>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_何同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值