您好,我正在我的项目中实现 Spring Oauth 2 框架,在请求访问 token 时出现 401 未授权错误,下面是我的代码。
public class Test {
public static void main(String[] args) {
RestTemplate restTemplate=new RestTemplate();
Map<String, String> map=new HashMap<String, String>();
map.put("grant_type", "password");
map.put("client_id", "test");
map.put("client_secret", "test");
map.put("username", "test");
map.put("password", "test");
String url="http://localhost:8080/SpringOauthServer/oauth/token?grant_type={grant_type}&client_id={client_id}&client_secret={client_secret}&username={username}&password={password}";
OauthToken result=restTemplate.getForObject(url, OauthToken.class,map);
System.out.println(result.getAccess_token());
}
}
但是当我使用下面的 curl 命令时,我得到了访问 token 。请帮助我在哪里我弄错了..
curl test:test@localhost:8080/SpringOauthServer/oauth/token -d grant_type=password -d client_id=test -d client_secret=test -d username=test -d password=test
响应:
{
"access_token":"d83a312b-323a-40a9-bfc4-c431c40f2ca8",
"token_type":"bearer",
"refresh_token":"17976f94-f3b7-4e2d-8726-3d094f7b1061",
"expires_in":43190,
"scope":"read write trust"
}
最佳答案
我知道这是一个旧线程,但如果有人坚持 RestTemplate
和 OAuth2
(例如,对于集成测试)它应该如何工作。
正在获取 OAuth2 access_token
使用 RestTemplate
在上面的问题中 grant_type=password
这意味着您需要发送 client_id
和 secret
在 authorization
http header 作为基本身份验证,您请求的其余信息作为表单数据进入 http 请求正文。
重用问题中的例子:
public class Test {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// Add the basic authentication "username:password"
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// Adding form data
Map<String, String> map = new HashMap<String, String>();
map.put("grant_type", "password");
map.put("client_id", "test");
map.put("username", "test");
map.put("password", "test");
map.put("scope", "read,write,trust");
// Creating HttpEntity request with the headers and form data
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
String url="http://localhost:8080/SpringOauthServer/oauth/token";
// Execute the request
ResponseEntity<String> response =
restTemplate
.withBasicAuth("test", "test")
.postForEntity(
url,
request,
OauthToken.class
);
System.out.println(result.getAccess_token());
}
}
问题出了什么问题:
curl
在问题中使用的功能与提供的 java 代码完全不同。
我会把它拆掉,别忘了检查documentation here
curl test:test
打电话curl
使用test
的基本身份验证作为用户名和test
作为密码(格式{USERNAME}:{PASSWORD}
),我们在RestTemplate
中也这样做了问题 java 代码中缺少它。localhost:8080/SpringOauthServer/oauth/token
curl
中使用的网址命令没有任何 url 参数,我们在RestTemplate
中也这样做了但它被添加到问题中,这是错误的。-d grant_type=password -d client_id=test -d client_secret=test -d username=test -d password=test
用-d
标记参数将使curl
执行 httpPOST
请求并发送这些参数作为我们在RestTemplate
中所做的相同的 http 正文中的表单数据。问题 java 代码中缺少它。
关于java - 为什么我在访问 token 时在 Spring Oauth2 中出现未经授权的 401 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241302/