简体   繁体   English

Android OAuth2资源所有者密码凭证授予

[英]Android OAuth2 Resource Owner Password Credentials Grant

The app needs to connect to a API that only support OAuth2 Resource Owner Password Credentials Grant. 该应用程序需要连接到仅支持OAuth2资源所有者密码凭据授予的API。 I tryed using the code bellow, but get the response code 400 "bad request". 我尝试使用下面的代码,但得到响应代码400“错误的请求”。 Using the same code I can connect to a normal site and retrive the content. 使用相同的代码,我可以连接到普通站点并检索内容。

I know that the API code is working because using Postman works. 我知道API代码可以正常工作,因为使用Postman可以正常工作。 In Postman I just make a post request, suppling the username, password, and grant_type, and using x-www-form-urlencoded 在Postman中,我只是发出一个发布请求,提供用户名,密码和grant_type,并使用x-www-form-urlencoded

The return of the connection is a json. 连接的返回是一个json。

Any ideas what it's wrong? 任何想法有什么问题吗? Should I use a 3rd party library? 我应该使用第三方图书馆吗? Any recomendations? 有什么建议吗? Thanks. 谢谢。

In the code I changed the credentials and the API link 在代码中,我更改了凭据和API链接

public class GetData extends AsyncTask<String, String, String> {

@Override
public String doInBackground(String... args) {

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://someaddress.azurewebsites.net/api/token");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("username", "some@email.com");
        urlConnection.setRequestProperty("password", "123");
        urlConnection.setRequestProperty("grant_type", "password");

        urlConnection.connect();

        int responseCode = urlConnection.getResponseCode();
        String responseMsg = urlConnection.getResponseMessage();
        if (responseCode >= 400 && responseCode <= 499) {
            throw new Exception(responseMsg + " :: " + responseCode);
        }

        InputStream in = urlConnection.getInputStream();
        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
}

@Override
protected void onPostExecute(String result) {

    //Do something with the JSON string

}
}

Adding some log, as sugested by Amod. 根据Amod的建议添加一些日志。 This is the return of the printStackTrace in the code above. 这是上面代码中的printStackTrace的返回。

12-12 01:16:33.210 8558-8643/com.marcussabino.tsftestedeconexo W/System.err: java.lang.Exception: Bad Request :: 400
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at com.marcussabino.tsftestedeconexo.GetData$override.doInBackground(GetData.java:40)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at com.marcussabino.tsftestedeconexo.GetData$override.access$dispatch(GetData.java)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at com.marcussabino.tsftestedeconexo.GetData.doInBackground(GetData.java:0)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at com.marcussabino.tsftestedeconexo.GetData.doInBackground(GetData.java:15)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-12 01:16:33.211 8558-8643/com.marcussabino.tsftestedeconexo W/System.err:     at java.lang.Thread.run(Thread.java:818)

I was understanding setRequestPorperty wrong!! 我在理解setRequestPorperty错误!

Thanks Nell and Stunner: https://stackoverflow.com/a/40576153/4276115 谢谢Nell和Stunner: https : //stackoverflow.com/a/40576153/4276115

Here is the code that worked for me: 这是对我有用的代码:

public class GetData extends AsyncTask<String, String, String> {

@Override
public String doInBackground(String... args) {
    String urlParameters  = "username=" + args[0] +
            "&password=" + args[1] +
            "&grant_type=" + args[2];

    byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int postDataLength = postData.length;

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://somesite.azurewebsites.net/api/token");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("charset", "utf-8");
        urlConnection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        urlConnection.setUseCaches(false);

        try(DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream())) {
            wr.write( postData );
        }

        int responseCode = urlConnection.getResponseCode();
        String responseMsg = urlConnection.getResponseMessage();
        if (responseCode >= 400 && responseCode <= 499) {
            throw new Exception(responseMsg + " :: " + responseCode);
        }

        InputStream in = urlConnection.getInputStream();

        BufferedReader  reader = new BufferedReader(new InputStreamReader(in));

        StringBuffer buffer = new StringBuffer();
        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
            Log.v("JSON", "> " + line);   //here you get the response

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
}

@Override
protected void onPostExecute(String result) {

    //Do something with the JSON string

}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android上使用资源所有者密码凭据实施OAuth2 - Implement OAuth2 with resource owner password credentials on Android 具有OAuth 2资源所有者密码凭证的Java scribe客户端 - Java scribe client with OAuth 2 Resource Owner Password Credentials 尝试为Android应用实现OAuth资源所有者密码流-我可以在数据库中存储刷新令牌吗? - Trying to implement OAuth resource owner password flow for an Android app - can I store refresh tokens in my database? OAuth2提供者:如何提供登录页面以便让oauth客户端获取资源所有者ID - OAuth2 Provider: How to offer a login page in order to let oauth clients get the resource owner id 适用于Android Google Play Oauth2 gtalk authToken的requestBody中的正确凭据 - Right credentials in requestBody for Android Google Play Oauth2 gtalk authToken OAuth2服务器设置&#39;client_id&#39;广告&#39;&#39;client_secret&#39;用于&#39;密码&#39;授权类型 - OAuth2 Server setup 'client_id' ad ''client_secret' for 'password' grant type Android上的Google oauth2 - google oauth2 on android oAuth2 Android方法 - oAuth2 Android approach 获取OAuth2凭据,以便在具有Google云端硬盘应用拥有的帐户的Android应用中使用 - Getting OAuth2 credentials for use in an Android application with a Google Drive application-owned account 以编程方式设置 Android 所有者密码 - Set Android owner password programmatically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM