Spring Boot Security(二)

Spring Security 配合 Thymeleaf 使用

注:Thymeleaf H5标注头:

xmlns:th="https://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

且 pom.xml 中

<!-- thymeleaf -->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- thymeleaf html5 注解提示 -->
<dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!--- end -->

一、登录页面

1、记住我

  • 在 Spring Security 中开启 rememberMe;
  • 登录验证表单中需携带 remember-me。

2、退出登录

  • 在 Spring Security 中进行登出配置

    // 登出配置
    http.logout()
         	.logoutUrl("/logout")
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .permitAll()
            .and()
            .csrf()
            .disable();
    
  • 向 logoutUrl 发送 post 请求即可

二、主页面

3、针对不同用户(权限)显示不同界面,利用 thymeleaf 模板引擎来实现

<div sec:authorize="!isAuthenticated()"><!--未认证用户-->
	请先登录<a href="/login">登录</a>
</div>
<div sec:authorize="isAuthenticated()"><!--已认证用户-->
	<h3><span sec:authentication="name"></span><span sec:authentication="principal.authorities"></span>你好!</h3>
</div>
<div sec:authorize="hasRole('ADMIN')">
	<h3>您有ADMIN权限</h3>
</div>
<div sec:authorize="hasRole('USER')">
	<h3>您有ADMIN权限</h3>
</div>
posted @ 2020-12-02 15:48  zolmk  阅读(102)  评论(0编辑  收藏  举报