spring security坑1:通過code獲取token報錯
DESC:
在postman中發起post請求“http://localhost:8127/oauth/token ”,
請求體:{"code":"6jttNy","client_id":"javaboy","client_secret":"123","grant_type":"authorization_code","redirect_uri":"http://localhost:8082/index.html"}
報錯如下:
ERROR1:
{
"timestamp": "2022-01-16T12:29:18.312+08:00",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/oauth/token"
}
RCA&SOLUTION:
請求參數應該放到form表單中,而非一個json格式的請求體。
多說一句,網上說需要把client_id和client_secret放到postman的Authorization區域中,如下圖所示,其實不需要,至少在我這個版本不需要:
ERROR2:
{
"error": "invalid_grant",
"error_description": "Invalid authorization code: 6jttNy"
}
RCA&SOLUTION:
因為我點擊頁面上的請求授權碼鏈接時,后端在請求完該code后,立刻使用該code去請求了token,而code被使用一次就失效了,所以我在postman中再次用code獲取token就報這個錯誤了。
另外,后端發起的請求代碼應該這么寫,這么寫就是發起一個表單傳遞參數的POST請求:
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("code", code);
map.add("client_id", "javaboy");
map.add("client_secret", "123");
map.add("redirect_uri", "http://localhost:8082/index.html");
map.add("grant_type", "authorization_code");
Map<String, String> resp = restTemplate.postForObject("http://localhost:8127/oauth/token", map, Map.class);
至於為什么要這么寫,請參考:https://blog.csdn.net/LDY1016/article/details/80002126