Android 应用程序的 RESTful Api 身份验证

log*_*ror 5 rest android json oauth oauth-2.0

我有一项任务,需要使用电子邮件和密码来验证用户身份并获取访问令牌。我有 api 密钥、秘密和基本 URL。我不需要为作业使用重定向 URL,而且也没有提供。我不确定使用哪种方法或哪个库。我淹没在大量的信息中,这让我感到困惑。我需要指出正确的方向......欢迎任何形式的帮助。谢谢

Pau*_*tha 4

根据您的评论,说明会告诉您使用Resource Owner Password Credentials Grant。您可以在规范中查看示例请求。

 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
Run Code Online (Sandbox Code Playgroud)

唯一看起来奇怪的事情(如果您从未遇到过)是Authorization标头值。阅读基本身份验证。基本上是(实际上)czZCaGRSa3F0MzpnWDFmQmF0M2JW的base64 编码。username:password<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();
Run Code Online (Sandbox Code Playgroud)

Base64使用的不是标准库类。而且它ObjectMapper不是标准库类。我只是用它来解析对类的令牌响应AccessToken。您可以使用任何您喜欢的解析器。该类AccessToken仅具有所有可能的标记值

public class AccessToken {
    public String access_token;
    public String refresh_token;
    public long expires_in;
    public String token_type;
    public String scope;
}
Run Code Online (Sandbox Code Playgroud)

从那里开始,一旦您拥有令牌,您想要发出的任何资源请求,您只需添加一个Authorization带有Bearer <access_token>.