HTTP請求
在Spring Security中的很多内容校驗都是通過對HTTP請求中的資料項進行的判斷
請求封包

基于RestClient插件了解請求封包
RestClient是VSCode的API測試插件,建立字尾為 .http
的檔案則會被VSCode識别成Rest Client的工具檔案
Get請求測試
建構Get請求
@GetMapping("/01")
public String firstApi() {
return "Hello World";
}
測試Get請求
- 直接編寫Get請求頭内容并發送請求
GET http://localhost:8080/test/01
- 由于沒有認證,Response Status為401
- 使用Basic Auth的方式添加請求頭【注意:Basic後面需要跟base64編碼的使用者名和密碼,但是Rest Client為了友善允許使用user + password的方式進行添加】
- 添加後發送請求
GET http://localhost:8080/test/01
Authorization: Basic user:0baf3007-ffa6-4ce1-96ea-efbb356cf3bd
- 請求發送成功,傳回Hello World
Put請求測試
建構Put請求
@PutMapping("/02")
public String secApi(@RequestParam String name) {
return "Hello " + name;
}
測試PUT請求
- 直接編寫Put請求頭内容以及Authentication請求頭并發送請求
PUT http://localhost:8080/test/02?name=Jack
Authorization: Basic user a08a4450-a0ff-4bdb-9b96-d31835ff2b40
- 發現請求始終提示403
- 開啟對于security的debug日志級别
logging.level.org.springframework.security.web=DEBUG
- 發現日志中錯誤:
Invalid CSRF token found for http://localhost:8080/test/02?name=Jack
- 添加security配置代碼,預先關閉csrf filter
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.httpBasic(Customizer.withDefaults())
.formLogin(form -> form.loginPage("/"));
}
}
- 再次發送請求,傳回Hello Jack
Post請求測試
建構Post請求
@PostMapping("/03")
public String thiApi(@RequestBody User user) {
return "Hello " + user.getName();
}
@Data
private class User {
String name;
String gender;
}
測試Post請求
- 直接編寫Post請求頭内容,Authentication請求頭以及請求體并發送請求
POST http://localhost:8080/test/03
Authorization: Basic user 5c11e9f9-c9d8-4322-8e5e-03fc36d91e6e
{
"name": "Susan",
"gender": "Man"
}
- 請求傳回415
Unsupported Media Type
- 添加Content-Type請求頭
POST http://localhost:8080/test/03
Authorization: Basic user 5c11e9f9-c9d8-4322-8e5e-03fc36d91e6e
Content-Type: application/json
{
"name": "Susan",
"gender": "Man"
}
- 再次發送請求,傳回Hello Susan
HTTP響應
響應封包
常用認證/授權相關狀态碼
- 401 - Unauthorized 未認證
- 403 - Forbidden 未授權