1. 程式人生 > 實用技巧 >Spring Boot Security(二)

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>