spring security坑1:通过code获取token报错

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

posted @ 2022-01-16 13:05  mediocrep  阅读(1088)  评论(0编辑  收藏  举报
既然选择了远方,便只顾风雨兼程!