我正在尝试实现基于Oauth2的Web服务。我有clientID,clientSecret,授权端点,令牌端点和回调Url(自定义架构指向Android本机页面)。当我检查其他基于Oauth2的API时,它有登录Url,它将被重定向到登录网页。但在我的情况下,没有登录URL,但应将其重定向到本机登录页面,并且在成功响应时,应将其重定向到登录本机页面。如何使用Oauth2获取访问令牌? 任何帮助将不胜感激。
答案 0 :(得分:2)
从上面的评论中,我们假设您已经将ASP.NET WebAPI作为服务器端应用程序,如果您的Android客户端应用程序使用HttpUrlConnection
,您可以参考以下示例代码(当然,您将需要修改更多以使其符合您的要求):
String address = "http://<IP>:<PORT>/token";
HttpURLConnection urlConnection;
String requestBody;
Uri.Builder builder = new Uri.Builder();
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "bnk");
stringMap.put("password", "bnk");
Iterator entries = stringMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
requestBody = builder.build().getEncodedQuery();
try {
URL url = new URL(address);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// do something...
} else {
// do something...
}
// do something...
} catch (Exception e) {
e.printStackTrace();
}
<强>更新强>
如果您更喜欢OkHttp,请参阅以下工作代码:
private class AccessTokenRequest extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String accessToken = null;
OkHttpJsonRequest jsonRequest = new OkHttpJsonRequest();
RequestBody requestBody = new FormEncodingBuilder()
.add("grant_type", "password")
.add("username", "bnk")
.add("password", "bnk123")
.build();
try {
JSONObject jsonObject = jsonRequest.post("http://192.168.1.100:24780/token", requestBody);
if (!jsonObject.isNull("access_token")) {
accessToken = jsonObject.getString("access_token");
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return accessToken;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
// do something such as storing the token for furture requests
}
}
public class OkHttpJsonRequest {
OkHttpClient client = new OkHttpClient();
JSONObject post(String url, RequestBody body) throws IOException, JSONException {
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return new JSONObject(response.body().string());
}
}
希望这有帮助!
答案 1 :(得分:1)
您可以使用this library from GitHub。