一,引入jar包,注意不要引入security
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
二,配置文件
# 端口號 server: port: 8080 spring: # thymeleaf配置 thymeleaf: enabled: true encoding: UTF-8 mode: HTML servlet: content-type: text/html prefix: classpath:/templates/ suffix: .html
三,創建一個不受保護的界面
Web頁面包含兩個簡單的視圖:index主頁和“hello”頁面,都定義在Thymeleaf模板中。
路徑:src/main/resources/templates/index.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Security Index</title> </head> <body> <h1>Index Page</h1> <a th:href="@{/hello}">點擊前往hello頁面</a> </body> </html>
路徑:src/main/resources/templates/hello.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <h1>Hello Spring Security</h1> </body> </html>
四,配置springmvc視圖控制器
由於web應用基於springmvc,因此需要配置視圖控制器來暴露這些模板
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class TemplateConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index").setViewName("index"); registry.addViewController("/hello").setViewName("hello"); registry.addViewController("/login").setViewName("login"); } }
運行main方法,並在瀏覽器地址欄輸入:http://localhost:8080/
如果看到index.html頁面,說明已經成功運行
點擊跳轉到hello頁面,無需任何認證即可進行跳轉
五,引入並使用Spring Security
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
package com.example.jwtdemo.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; /** * @author Jensen Zhan */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/index").permitAll() // permitAll被允許訪問 .anyRequest().authenticated() // 其余的請求需要認證后才可允許訪問 .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() // 在內存中進行身份驗證 .passwordEncoder(new BCryptPasswordEncoder()) .withUser("user") .password(new BCryptPasswordEncoder().encode("123456")) .roles("USER"); } }
【說明】:
-
WebSecurityConfig類使用了@EnableWebSecurity注解,以啟用Spring Security的Web安全支持。
-
configure(HttpSecurity)方法自定義有哪些url需要被認證,哪些不需要。當用戶登錄后將會被重定向請求到需要身份認證的頁面(hello.html),否則在用戶未登錄的情況下將會跳轉到登錄頁面
-
configure(AuthenticationManagerBuilder)方法用於設置認證的條件保存於內存中,用戶名為“user”,密碼為“123456”,角色為User。同時該方法也可以修改認證方式為jdbc進行認證
創建登錄頁面(認證時需要用到)
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> </head> <body> <div th:if="${param.error}"> 用戶名或密碼不正確 </div> <div th:if="${param.logout}"> 你已經退出登錄 </div> <form th:action="@{/login}" method="post"> <div><label> 用戶名: <input type="text" name="username"/> </label></div> <div><label> 密 碼: <input type="password" name="password"/> </label></div> <div><input type="submit" value="登錄"/></div> </form> </body> </html>
修改hello.html
在認證成功后跳轉到hello.html頁面,我們希望能夠看到登錄的用戶名,同時允許用戶退出登錄,因此我們需要修改hello.html頁面
路徑:src/main/resources/templates/hello.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="退出登錄" /> </form> </body> </html>
【說明】:
-
我們在hello.html頁面中使用了HttpServletRequest#getRemoteUser()的thymeleaf集成來顯示用戶名。
-
頁面中退出登錄表單會將請求提交到"/logout",成功注銷后程序會重定向到"/login?logout"