我有一项任务需要使用电子邮件和密码来验证用户并获取访问 token 。我同时拥有 api key 、 secret 和基本 URL。我不需要为作业使用重定向 URL,也没有提供。我不确定要使用哪种方法或哪个库。我淹没在大量的信息中,这让我感到困惑。我需要指出正确的方向......欢迎任何形式的帮助。谢谢
最佳答案
根据您的评论,说明告诉您使用 Resource Owner Password Credentials Grant .你可以看到一个 example request在规范中。
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w
唯一可能看起来很奇怪的事情(如果您从未遇到过)是 Authorization
header 值。继续阅读 Basic Authentication .基本上是 czZCaGRSa3F0MzpnWDFmQmF0M2JW
是 username:password
的 base64 编码(实际上是 <client_id>:<client_secret>
)。
如果不使用任何外部库(只是标准的 Java 库)来发出请求,您可能会有类似的东西
String formData = "username=<uname>&password=<pass>&grant_type=password";
String header = "Basic " + Base64.encodeAsString("<client_id>:<client_secret>");
HttpURLConnection connection
= (HttpURLConnection) new URL(tokenUrl).openConnection();
connection.setDoOutput(true);
connection.addRequestProperty("Authorization", header);
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(formData.length()));
OutputStream out = connection.getOutputStream();
out.write(formData.getBytes(StandardCharsets.UTF_8));
InputStream in = connection.getInputStream();
AccessToken token = new ObjectMapper().readValue(in, AccessToken.class);
System.out.println(token);
out.close();
in.close();
Base64
我用的不是标准库类。还有 ObjectMapper
不是标准库类。我只是用它来解析对 AccessToken
的 token 响应类(class)。您可以使用任何您喜欢的解析器。 AccessToken
类只有所有可能的标记值
public class AccessToken {
public String access_token;
public String refresh_token;
public long expires_in;
public String token_type;
public String scope;
}
从那里,一旦你有了 token ,你想要发出的任何资源请求,你只需要添加一个 Authorization
带有 Bearer <access_token>
的 header .
关于android - Android 应用的 RESTful Api 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147709/