Implementing Oauth2 with login credentials from na

2020-04-27 19:38发布

问题:

I am trying to implement Oauth2 based web service. I have clientID, clientSecret, Authorization endpoint, Token endpoint and callback Url(custom schema points to an android native page). When I checked other Oauth2 based APIs, it has login Url and it will be redirected to a login web page. But in my case there is not Login URL, but it should be redirected to a native login page and on success response it should be redirected to logged in native page. How to get the access token using Oauth2? Any help will be appreciated.

回答1:

From the comments above, let's assume you have already had ASP.NET WebAPI as server-side app, and if your Android client app uses HttpUrlConnection, you can refer to the following sample code (of course, you will need to modify more to make it works as your requirement):

            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();
            }

UPDATE:

If you prefer OkHttp, please refer to the following working code:

    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());
        }
    }

Hope this helps!



回答2:

You can use this library from GitHub.