在 Android 上将 OAuth 与 Scribe 结合使用

发布于 2024-11-27 17:39:26 字数 5308 浏览 1 评论 0原文

您好,我正在使用 scribe 库与 LInkedIn 进行 OAuth 通信。

我有一个登录类和一个查询类。

登录类创建一个服务来获取我的请求令牌和秘密,并创建我的访问令牌。然后,访问令牌将保存到首选项文件中。这似乎工作正常,我可以在创建所有令牌后成功进行 api 调用。

在我的 OAuth 查询类中,我检索访问令牌,创建另一个服务并尝试进行 API 调用,但是当我加载调用此类的活动时,它会导致我的应用程序崩溃。我已经测试过以确保访问令牌已保存并且确实如此。

这是我的登录类

public class Login_LinkedIn extends Activity 
{
SharedPreferences settings;
OAuthService service;
Token requestToken;

Button home;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webauth);

    initControls();

    service = new ServiceBuilder()
    .provider(LinkedInApi.class)
    .apiKey( getString(R.string.apiKey) )
    .apiSecret( getString(R.string.secKey) )
    .callback( getString(R.string.callBack) )
    .build();

    requestToken = service.getRequestToken();
    final String authURL = service.getAuthorizationUrl(requestToken);

    final WebView webview = (WebView) findViewById(R.id.webView);

    //attach WebViewClient to intercept the callback url
    webview.setWebViewClient(new WebViewClient()
    {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {

            //check for our custom callback protocol
            //otherwise use default behavior
            if(url.startsWith( getString(R.string.callBack) ))
            {
                //authorization complete hide webview for now.
                webview.setVisibility(View.GONE);
                Uri uri = Uri.parse(url);
                String verifier = uri.getQueryParameter("oauth_verifier");
                Verifier v = new Verifier(verifier);

                //save this token for practical use.
                Token accessToken = service.getAccessToken(requestToken, v);

                OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/people/~:(first-name,last-name)");
                service.signRequest(accessToken, request);
                Response response = request.send();

                xmlHandler xh = new xmlHandler(response.getBody());

                settings = getSharedPreferences("preferences", 0);
                SharedPreferences.Editor editor = settings.edit();

                editor.putString("accessToken", accessToken.getToken());

                // The requestToken is saved for use later on to verify the OAuth request.
                // See onResume() below
                editor.putString("requestToken", requestToken.getToken());
                editor.putString("requestSecret", requestToken.getSecret());

                editor.putString("first-name", xh.getValue("first-name"));
                editor.putString("last-name", xh.getValue("last-name"));

                editor.commit();

                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
   });

   //send user to authorization page
   webview.loadUrl(authURL); 
}

@Override
protected void onResume()
{
    super.onResume();

    Intent i = getIntent();

    if(i != null) 
    {
        Uri uri = i.getData();
        if(uri != null)
        {
            String oauthVerifier = uri.getQueryParameter("oauth_verifier");

            Verifier verifier = new Verifier(oauthVerifier);

            requestToken = new Token(settings.getString("requestToken", null), settings.getString("requestSecret", null));

            Token accessToken = service.getAccessToken(requestToken, verifier);

            // Save the access token.
            SharedPreferences.Editor editor = settings.edit();
            editor.remove("requestToken");
            editor.remove("requestSecret");
            editor.putString("accessToken", accessToken.getToken());
            editor.putString("accessSecret", accessToken.getSecret());
            editor.commit();

            // Start the film list activity.
            final Intent intent = new Intent(this,ProConnect.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
} 

private void initControls()
{
    home = (Button)findViewById(R.id.home);

    final Intent intent = new Intent(this,ProConnect.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    home.setOnClickListener(new Button.OnClickListener() 
    {
        public void onClick (View v) 
        {
            startActivity(intent);
        }
    });


}

}

和查询类

public class oAuthQuery extends Activity
{
OAuthService service;
Token accessToken;
SharedPreferences settings;

public oAuthQuery()
{
    service= new ServiceBuilder()
    .provider(LinkedInApi.class)
    .apiKey( getString(R.string.apiKey) )
    .apiSecret( getString(R.string.secKey) )
    .callback( getString(R.string.callBack) )
    .build();

    settings = getSharedPreferences("preferences", 0);

    accessToken = new Token(settings.getString("accessToken", null), settings.getString("accessSecret", null));

}

public String query(String s)
{
    OAuthRequest request = new OAuthRequest(Verb.GET, s);
    service.signRequest(accessToken, request);
    Response response = request.send();

    return response.getBody();
}

public OAuthService getService()
{
    return service;
}

}

感谢您的帮助 杰夫

Hi I'm using the scribe library for OAuth communication with LInkedIn.

I have a login class and a query class.

The login class creates a service to get my request token and secret and creates my access token. The access token is then saved to the preferences file. This seems to work fine and I can make a successful api call after all the tokens have been created.

In my OAuth query class i retrieve the access token, create another service and try to make an API call, but when ever I load an activity which makes calls this class it causes my app to crash. I have tested to make sure that the access token is saved and they are.

Here is my login class

public class Login_LinkedIn extends Activity 
{
SharedPreferences settings;
OAuthService service;
Token requestToken;

Button home;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webauth);

    initControls();

    service = new ServiceBuilder()
    .provider(LinkedInApi.class)
    .apiKey( getString(R.string.apiKey) )
    .apiSecret( getString(R.string.secKey) )
    .callback( getString(R.string.callBack) )
    .build();

    requestToken = service.getRequestToken();
    final String authURL = service.getAuthorizationUrl(requestToken);

    final WebView webview = (WebView) findViewById(R.id.webView);

    //attach WebViewClient to intercept the callback url
    webview.setWebViewClient(new WebViewClient()
    {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {

            //check for our custom callback protocol
            //otherwise use default behavior
            if(url.startsWith( getString(R.string.callBack) ))
            {
                //authorization complete hide webview for now.
                webview.setVisibility(View.GONE);
                Uri uri = Uri.parse(url);
                String verifier = uri.getQueryParameter("oauth_verifier");
                Verifier v = new Verifier(verifier);

                //save this token for practical use.
                Token accessToken = service.getAccessToken(requestToken, v);

                OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/people/~:(first-name,last-name)");
                service.signRequest(accessToken, request);
                Response response = request.send();

                xmlHandler xh = new xmlHandler(response.getBody());

                settings = getSharedPreferences("preferences", 0);
                SharedPreferences.Editor editor = settings.edit();

                editor.putString("accessToken", accessToken.getToken());

                // The requestToken is saved for use later on to verify the OAuth request.
                // See onResume() below
                editor.putString("requestToken", requestToken.getToken());
                editor.putString("requestSecret", requestToken.getSecret());

                editor.putString("first-name", xh.getValue("first-name"));
                editor.putString("last-name", xh.getValue("last-name"));

                editor.commit();

                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
   });

   //send user to authorization page
   webview.loadUrl(authURL); 
}

@Override
protected void onResume()
{
    super.onResume();

    Intent i = getIntent();

    if(i != null) 
    {
        Uri uri = i.getData();
        if(uri != null)
        {
            String oauthVerifier = uri.getQueryParameter("oauth_verifier");

            Verifier verifier = new Verifier(oauthVerifier);

            requestToken = new Token(settings.getString("requestToken", null), settings.getString("requestSecret", null));

            Token accessToken = service.getAccessToken(requestToken, verifier);

            // Save the access token.
            SharedPreferences.Editor editor = settings.edit();
            editor.remove("requestToken");
            editor.remove("requestSecret");
            editor.putString("accessToken", accessToken.getToken());
            editor.putString("accessSecret", accessToken.getSecret());
            editor.commit();

            // Start the film list activity.
            final Intent intent = new Intent(this,ProConnect.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
} 

private void initControls()
{
    home = (Button)findViewById(R.id.home);

    final Intent intent = new Intent(this,ProConnect.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    home.setOnClickListener(new Button.OnClickListener() 
    {
        public void onClick (View v) 
        {
            startActivity(intent);
        }
    });


}

}

and my query class

public class oAuthQuery extends Activity
{
OAuthService service;
Token accessToken;
SharedPreferences settings;

public oAuthQuery()
{
    service= new ServiceBuilder()
    .provider(LinkedInApi.class)
    .apiKey( getString(R.string.apiKey) )
    .apiSecret( getString(R.string.secKey) )
    .callback( getString(R.string.callBack) )
    .build();

    settings = getSharedPreferences("preferences", 0);

    accessToken = new Token(settings.getString("accessToken", null), settings.getString("accessSecret", null));

}

public String query(String s)
{
    OAuthRequest request = new OAuthRequest(Verb.GET, s);
    service.signRequest(accessToken, request);
    Response response = request.send();

    return response.getBody();
}

public OAuthService getService()
{
    return service;
}

}

Thanks for any help
Jeff

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红衣飘飘貌似仙 2024-12-04 17:39:26

我解决了这个问题,最后发现这是一件愚蠢的事情。我已经编辑了代码来保存访问密钥和访问令牌,但在手机上测试我的应用程序时忘记重新登录。这导致无法访问保存令牌部分的代码。

我在 LinkedIn API 中使用邀请调用时仍然遇到问题,

invite.setOnClickListener(new Button.OnClickListener() 
        {
            public void onClick (View v) 
            {
                inviteXml = inviteCreator.inviteString(to, subj, body, authName, authValue);
                nameField.setText(inviteXml);
                titleField.setText("");


                call = "http://api.linkedin.com/v1/people/~/mailbox";
                request = new OAuthRequest(Verb.GET, call);
                request.addPayload(inviteXml);
                service.signRequest(accessToken, request);
                response = request.send();

                invite.setVisibility(View.GONE);
            }
        });

我不确定这是否是将 XML 字符串添加到调用的正确方法。 LinkedIn API 没有指定如何添加它。有人有这方面的经验吗?

I solved the problem it was something stupid in the end. I had edited my code to save the access secret and the the access token but had forgotten to re-login when testing my app on my phone. This resulted in the code which saved the parts of the token was not being reached.

I still have a problem using the invite call in the LinkedIn API

invite.setOnClickListener(new Button.OnClickListener() 
        {
            public void onClick (View v) 
            {
                inviteXml = inviteCreator.inviteString(to, subj, body, authName, authValue);
                nameField.setText(inviteXml);
                titleField.setText("");


                call = "http://api.linkedin.com/v1/people/~/mailbox";
                request = new OAuthRequest(Verb.GET, call);
                request.addPayload(inviteXml);
                service.signRequest(accessToken, request);
                response = request.send();

                invite.setVisibility(View.GONE);
            }
        });

I'm not sure if this is the correct way to add the XML string to the call. The LinkedIn API doesn't specify how it is to be added. Has anyone any experience with this?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文