一、入門案例
Spring Security 自定義登錄界面
通過之前的一節 01-Spring Security框架學習--入門(一)的簡單演示,Spring security 使用框架自帶的登錄界面,下面的案例將使用自己定義的登錄頁面。
基本步驟
- 添加如下頁面:
- 登錄界面
src/main/webapp/login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<h3>自定義的登錄界面</h3>
<form action="/login" method="post">
用戶名: <input type="text" name="username"><br>
密碼: <input type="password" name="password"><br>
<input name="submit" type="submit" value="登陸">
</form>
</body>
</html>
- 登錄結果頁面
src/main/webapp/login_error.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄錯誤</title>
</head>
<body>
<span style="color:red">用戶名或密碼錯誤,無權訪問!</span>
</body>
</html>
- 修改Spring-security.xml 配置
src/main/resources/spring/spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 設置不用不用登陸規則(注意:路徑前'/'符號不可省略) -->
<http pattern="/login.html" security="none"></http>
<http pattern="/login_error.html" security="none"></http>
<!-- 頁面的鏈接規則 -->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_ADMIN" />
<!-- 開啓表單提交功能(注意:路徑前'/'符號不可省略)-->
<form-login login-page="/login.html" default-target-url="/index.html" authentication-failure-url="/login_error.html"/>
<!-- 關閉 csrf 攔截 -->
<csrf disabled="true"/>
</http>
<!-- 認證管理器 -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>manager>
</beans:beans>
運行效果
運行問題
- 如下錯誤:
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
這是由於Spring security 默認開啓防範CSRF攻擊導致,目前demo演示關閉即可。
二、Spring security 的總結
通過路上的簡單的配置,Spring security 爲我們將我們很多的事情:
- 在你的應用中每個URL都要求認證
- 爲你生成一個登陸表單
- 允許用戶在表單中提交 Username 用戶名爲user 以及 Password 密碼爲 password 來進行認證
- 允許用戶註銷
- 防範CSRF攻擊
- 防範Session Fixation
- 集成Security Header
spring security的基本原理
spring 通過servlet的攔截器``攔截HTTP請求,在這個過濾鏈的作用下用戶認證和授權。
如果想深入瞭解原理流程【請移步】