⒈添加starter依賴
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-security</artifactId> 9 </dependency> 10 11 <dependency> 12 <groupId>org.springframework.boot</groupId> 13 <artifactId>spring-boot-starter-thymeleaf</artifactId> 14 </dependency> 15 16 <!--添加Thymeleaf Spring Security依賴--> 17 <dependency> 18 <groupId>org.thymeleaf.extras</groupId> 19 <artifactId>thymeleaf-extras-springsecurity4</artifactId> 20 <version>3.0.4.RELEASE</version> 21 </dependency>
⒉使用配置類定義授權與定義規則
1 package cn.coreqi.config; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 5 import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 9 //@Configuration 10 @EnableWebSecurity 11 public class SecurityConfig extends WebSecurityConfigurerAdapter { 12 13 //定義授權規則 14 @Override 15 protected void configure(HttpSecurity http) throws Exception { 16 //定制請求授權規則 17 http.authorizeRequests() 18 .antMatchers("/css/**","/js/**","/fonts/**","index").permitAll() //不攔截,直接訪問 19 .antMatchers("/vip1/**").hasRole("VIP1") 20 .antMatchers("/vip2/**").hasRole("VIP2") 21 .antMatchers("/vip3/**").hasRole("VIP3"); 22 //開啟登陸功能(自動配置) 23 //如果沒有登陸就會來到/login(自動生成)登陸頁面 24 //如果登陸失敗就會重定向到/login?error 25 //默認post形式的/login代表處理登陸 26 http.formLogin().loginPage("/userLogin").failureUrl("/login-error"); 27 //開啟自動配置的注銷功能 28 //訪問/logout表示用戶注銷,清空session 29 //注銷成功會返回/login?logout頁面 30 //logoutSuccessUrl()設置注銷成功后跳轉的頁面地址 31 http.logout().logoutSuccessUrl("/"); 32 //開啟記住我功能 33 //登陸成功以后,將cookie發給瀏覽器保存,以后訪問頁面帶上這個cookie,只要通過檢查就可以免登陸 34 //點擊注銷會刪除cookie 35 http.rememberMe(); 36 } 37 38 //定義認證規則 39 @Override 40 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 41 //jdbcAuthentication() 在JDBC中查找用戶 42 //inMemoryAuthentication() 在內存中查找用戶 43 44 auth.inMemoryAuthentication().withUser("fanqi").password("admin").roles("VIP1","VIP2","VIP3") 45 .and() 46 .withUser("zhangsan").password("123456").roles("VIP1"); 47 } 48 }
⒊編寫控制器類(略)
⒋編寫相關頁面
1 <!DOCTYPE html> 2 <html lang="en" 3 xmlns:th="http://www.thymeleaf.org" 4 xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" 5 xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> 6 <head> 7 <meta charset="UTF-8"> 8 <title>登錄頁面</title> 9 </head> 10 <body> 11 <div sec:authorize="isAuthenticated()"> 12 <p>用戶已登錄</p> 13 <p>登錄的用戶名為:<span sec:authentication="name"></span></p> 14 <p>用戶角色為:<span sec:authentication="principal.authorities"></span></p> 15 </div> 16 <div sec:authorize="isAnonymous()"> 17 <p>用戶未登錄</p> 18 </div> 19 </body> 20 </html>