springboot+springsecurity+thymeleaf


來源:聽秦疆老師的課筆記

springsecurity是一個權限管理框架,用來授權,認證,加密等等......類似的工具還有shiro

1.整合

  我用的是springboot2.2.0版本,導入以下依賴。

  spring和security整合包我用的版本是thymeleaf-extras-springsecurity5,
  老師用的是thymeleaf-extras-springsecurity4
  如果使用thymeleaf-extras-springsecurity4,需要將springboot的版本調低至2.0.9及以下
  springbo
ot和springsecurity版本不匹配,會產生thymeleaf和security聯合使用不生效問題
 1 <dependencies>
 2 
 3         <dependency>
 4             <groupId>org.springframework.boot</groupId>
 5             <artifactId>spring-boot-starter-thymeleaf</artifactId>
 6         </dependency>
 7 
 8         <dependency>
 9             <groupId>org.springframework.boot</groupId>
10             <artifactId>spring-boot-starter-security</artifactId>
11         </dependency>
12         <!-- thymeleaf和Security整合依賴 -->
13         <dependency>
14             <groupId>org.thymeleaf.extras</groupId>
15             <artifactId>thymeleaf-extras-springsecurity5</artifactId>
16             <version>3.0.3.RELEASE</version>
17         </dependency>
18 
19         <dependency>
20             <groupId>org.springframework.boot</groupId>
21             <artifactId>spring-boot-starter-web</artifactId>
22         </dependency>
23 
24         <dependency>
25             <groupId>org.springframework.boot</groupId>
26             <artifactId>spring-boot-starter-test</artifactId>
27             <scope>test</scope>
28             <exclusions>
29                 <exclusion>
30                     <groupId>org.junit.vintage</groupId>
31                     <artifactId>junit-vintage-engine</artifactId>
32                 </exclusion>
33             </exclusions>
34         </dependency>
35     </dependencies>
View Code

2.配置使用

  使用方式十分簡單,用一個類繼承WebSecurityConfigurerAdapter並重寫方法即可

   不要忘記使用@EnableWebSecurity開啟服務,交給spring管理

    

 1 /**
 2  * @author Silent
 3  * @date 2019/11/13 17:12:38
 4  * @description  @EnableWebSecurity 開啟服務
 5  * 1.授權
 6  * 2.認證
 7  */
 8 @EnableWebSecurity
 9 public class SecurityConfig extends WebSecurityConfigurerAdapter {
10     /**
11      *
12      * @param http
13      * @throws Exception
14      * 授權:首頁所有人可以訪問,功能頁只有對應有權限的人才能訪問
15      */
16     @Override
17     protected void configure(HttpSecurity http) throws Exception {
18         // 請求授權的規則~
19         http.authorizeRequests()
20                 .antMatchers("/").permitAll()
21                 .antMatchers("/level1/**").hasRole("vip1")
22                 .antMatchers("/level2/**").hasRole("vip2")
23                 .antMatchers("/level3/**").hasRole("vip3");
24         // 沒有權限默認會到登錄頁面(security內置的登錄頁面),需要開啟登錄頁面
25         //定制登錄頁面loginPage("/toLogin")
26         //默認表單name用戶名是username,密碼是password,自己定義需要usernameParameter("username").passwordParameter("password")
27         //loginProcessingUrl("/login");參數“login”與登錄表單的action保持一致
28         /**
29          * 如果只配置loginPage而不配置loginProcessingUrl的話
30          * 那么loginProcessingUrl默認就是loginPage
31          * 你配置的loginPage("/toLogin") ,那么loginProcessingUrl就是"/toLogin",相應的action也改為“/toLogin”
32          */
33         http.formLogin().loginPage("/toLogin")
34                 .usernameParameter("username").passwordParameter("password")
35                 .loginProcessingUrl("/login");
36         //防止網站攻擊 csrf,阻止get,
37         http.csrf().disable();//關閉csrf功能,解決登錄失敗
38         //開啟注銷功能,跳到首頁
39         http.logout().logoutSuccessUrl("/");
40         //開啟記住我功能,cookies默認保存兩周,自定義接受前端參數
41         http.rememberMe().rememberMeParameter("remember");
42 
43     }
44 
45     //認證, springboot 2.1.x可以直接使用
46 
47     @Override
48     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
49         //正常的話,這些數據應該從數據庫讀取 這里寫入內存
50         auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
51                 .withUser("silent").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
52                 .and()
53                 .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
54                 .and()
55                 .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
56     }
57 
58 }

3.在thymeleaf中使用springsecurity

  sec:authorize :判斷信息是否存在

    sec:authentication:取出相應的值

  1 <!DOCTYPE html>
  2 <html lang="en" xmlns:th="http://www.thymeleaf.org"
  3       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
  4 <head>
  5     <meta charset="UTF-8">
  6     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  7     <title>首頁</title>
  8     <!--semantic-ui-->
  9     <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
 10     <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
 11 </head>
 12 <body>
 13 
 14 <!--主容器-->
 15 <div class="ui container">
 16 
 17     <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
 18         <div class="ui secondary menu">
 19             <a class="item"  th:href="@{/index}">首頁</a>
 20 
 21             <!--登錄注銷-->
 22             <div class="right menu">
 23                 <!--未登錄-->
 24                 <div sec:authorize="!isAuthenticated()">
 25                     <a class="item" th:href="@{/toLogin}" >
 26                         <i class="address card icon"></i> 登錄
 27 
 28                     </a>
 29                 </div>
 30                 <!--已登錄 -->
 31                 <div sec:authorize="isAuthenticated()">
 32                     <a class="item">
 33                         用戶名:<span sec:authentication="name"></span>
 34                         角色: <span sec:authentication="principal.authorities"></span>
 35                     </a>
 36                 </div>
 37                 <div sec:authorize="isAuthenticated()">
 38                     <a class="item" th:href="@{/logout}" >
 39                         <i class="sign-out icon"></i> 注銷
 40                     </a>
 41                 </div>
 42 
 43             </div>
 44         </div>
 45     </div>
 46 
 47     <div class="ui segment" style="text-align: center">
 48         <h3>Spring Security Study by 秦疆</h3>
 49     </div>
 50 
 51     <div>
 52         <br>
 53         <div class="ui three column stackable grid">
 54             <div class="column"  sec:authorize="hasRole('vip1')">
 55                 <div class="ui raised segment">
 56                     <div class="ui">
 57                         <div class="content">
 58                             <h5 class="content">Level 1</h5>
 59                             <hr>
 60                             <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
 61                             <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
 62                             <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
 63                         </div>
 64                     </div>
 65                 </div>
 66             </div>
 67 
 68             <div class="column"  sec:authorize="hasRole('vip2')">
 69                 <div class="ui raised segment">
 70                     <div class="ui">
 71                         <div class="content">
 72                             <h5 class="content">Level 2</h5>
 73                             <hr>
 74                             <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
 75                             <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
 76                             <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
 77                         </div>
 78                     </div>
 79                 </div>
 80             </div>
 81 
 82             <div class="column"  sec:authorize="hasRole('vip3')">
 83                 <div class="ui raised segment">
 84                     <div class="ui">
 85                         <div class="content">
 86                             <h5 class="content">Level 3</h5>
 87                             <hr>
 88                             <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
 89                             <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
 90                             <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
 91                         </div>
 92                     </div>
 93                 </div>
 94             </div>
 95 
 96         </div>
 97     </div>
 98     
 99 </div>
100 
101 
102 <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
103 <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
104 
105 </body>
106 </html>
View Code

 

 https://github.com/Sevenwsq/springsecurity-demo/tree/springsecurity-demo 項目地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM