从本地登录页面的登录凭据实现的OAuth2 [英] Implementing Oauth2 with login credentials from native login page

查看:649
本文介绍了从本地登录页面的登录凭据实现的OAuth2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现的OAuth2基于Web服务。我有客户端ID,clientSecret,授权终点,终点令牌和回调URL(自定义模式指向一个Android原生页)。当我检查其他基于API的OAuth2用户,它已经登录网址,它会被重定向到一个登录网页。但在我的情况下,有没有登录的网址,但它应该被重定向到一个本地登录页面和成功响应应该被重定向到登录页面本土。如何使用OAuth2用户获得访问令牌?
任何帮助将AP preciated。

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.

推荐答案

从上面的意见,让我们假设你已经有ASP.NET的WebAPI服务器端应用程序,如果你的Andr​​oid客户端应用程序使用 HttpURLConnection类,你可以参考code以下示例(当然,你将需要修改更能让它可以作为你的要求):

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

更新:

如果您preFER OkHttp ,请参考以下工作code:

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

希望这有助于!

这篇关于从本地登录页面的登录凭据实现的OAuth2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆