使用 JOAuth 进行 OAuth 1 授权,需要示例 [英] OAuth 1 authorization with JOAuth, example needed

查看:15
本文介绍了使用 JOAuth 进行 OAuth 1 授权,需要示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我在 LinkedIn/Twitter 中看到有关如何进行 OAuth 1 3-legged 或 2-legged 授权的问题,所以我想我会发布一个示例,说明我如何使用 JOAuth.

Since I've seen questions about how to do OAuth 1 3-legged or 2-legged authorization in LinkedIn/Twitter, I thought I'll post an example of how I've achieved to authorize to Twitter with JOAuth.

推荐答案

这是如何从 Twitter 检索访问令牌 net.oauth.token.v1.AccessToken.

This is how to retrieve an Access Token net.oauth.token.v1.AccessToken from Twitter.

首先,您需要来自 Twitter 的 2 个东西,您需要在 Twitter 上注册您的应用程序并获取应用程序:

First, you will need 2 things from Twitter, which you are required to register your application to Twitter and get an application:

  • API 密钥(OAuth 称之为消费者密钥)
  • API 秘密(OAuth 称之为消费者秘密).

现在,我们将向 Twitter 进行身份验证:

Now, Here is the how we'll authenticate to Twitter:

首先,让我们拥有包含 API 密钥的 2 个方法 &秘密:

first, let's have our 2 methods that contains our API key & secret:

private static final String API_KEY = "TWITTER_API_KEY_HERE";
private static final String API_SECRET  = "TWITTER_API_SECRET_HERE";

哦,是的,我们需要一个 callback_url:

Oh yes, we need a callback_url:

private static final String CALLBACK_URL = "oob";

稍后我将解释 oob(带外).

I'll explain oob (Out-of-Band) later.

然后,我们需要创建一个消费者来为我们进行 OAuth 授权:

Then, we need to create a consumer that will do the OAuth authorization for us:

private OAuth1Consumer consumer = new OAuth1Consumer(API_KEY, API_SECRET, new OAuth1ServiceProvider("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/authorize", "https://api.twitter.com/oauth/access_token"));

参数如下:API Key,接下来是API Secret,OAuth服务提供者(由Request Token URL、Authorize Token URL、Access Token URL组成).

The parameters are as follows: API Key, next is API Secret, OAuth service provider (consisting of Request Token URL, Authorize Token URL, Access Token URL).

现在,让乐趣开始吧:

请求(未经授权的)请求令牌:

要获取请求令牌,我们需要从OAuth1Consumer 类中调用requestUnauthorizedToken:

To obtain a request token, we need to call the requestUnauthorizedToken from OAuth1Consumer class:

RequestToken requestToken = consumer.requestUnauthorizedToken(null, CALLBACK_URL, null, new OAuthHmacSha1Signature());

第一个参数是 realm,它为空(因为 Twitter 并没有真正使用它),然后是 callback_url 和一个签名方法.

The first parameter is realm which is null (as Twitter doesn't really use it), then the callback_url, and a signature method.

有 3 种有效的 OAuth 签名方法:

There are 3 valid OAuth Signature method:

  • PLAINTEXT(按原样以纯文本形式发送),OAuthPlainTextSignature 类.
  • HMAC-SHA1,OAuthHmacSha1Signature 类.
  • RSA-SHA1,OAuthRsaSha1Signature 类.
  • PLAINTEXT (send as is, in plaintext), class OAuthPlainTextSignature.
  • HMAC-SHA1, class OAuthHmacSha1Signature.
  • RSA-SHA1, class OAuthRsaSha1Signature.

Twitter 使用 HMAC-SHA1,请在对其他提供商进行 OAuth 时参考文档.

Twitter uses HMAC-SHA1, please refer to documentations when doing OAuth to other providers.

现在我们有一个未授权的请求令牌,让我们对其进行授权.

Now that we have an unauthorized request token, let's authorize it.

授权(未经授权的)请求令牌:

授权要求用户转到服务提供商的 URL 并登录,因此我们需要一个可以在浏览器中重定向到的 URL.

Authorization requires the user to go to the service provider url and signing in, therefore we need a URL that we can redirect to in our browser.

String url = consumer.createOAuthUserAuthorizationUrl(requestToken, null);

(第二个参数是 null 因为我们没有额外的 HTTP 参数要发送,但是如果你这样做了,创建一个 Map 属性, 填充它们并在方法调用中分块 :))

(The 2nd parameter is null as we don't have additional HTTP parameters to send through, but if you do, create a Map<String, String> attributes, fill them and chunk it in the method call :))

现在我们有了 URL,将 URL 发送到浏览器,授权应用程序,这是 callback_url 的用武之地:

Now that we have the URL, chuck the URL to the browser, authorize the application and here is where the callback_url comes in:

带外 (OOB) 授权

OOB 授权用于无法执行 HTTP 重定向但仍想请求访问令牌的应用程序.Twitter 声明使用 PIN 码代替 HTTP 重定向.该 PIN(在授权 Twitter 应用程序后显示)由 Twitter 在浏览器上显示为图像.如需更多信息,请参阅Twitter OAuth API 文档.

OOB authorization is used for applications that can't do an HTTP Redirect but still want to request an Access Token. Twitter states that a PIN is used instead of HTTP Redirect. That PIN (displayed after authorising the Twitter Application) is displayed by Twitter as an image on a browser. For more information, refer to Twitter OAuth API Documentation.

在基于 OOB 的调用中,一旦您授权应用程序,Twitter 会向您发送一个 PIN:看到该 PIN 后,要获取访问令牌,请执行以下操作:

In OOB based call, once you authorized the application, Twitter sends you a PIN: Once you see the pin, to get the Access Token, do the following:

String twitterPin = ""; //Whatever Twitter displayed
AccessToken accessToken = example.requestAccessToken(new AuthorizedToken(requestToken.getToken(), twitterPin), requestToken);

我们开始吧.

调用访问令牌后,真正的访问令牌值位于 AccessToken.getToken() 方法中.

Once you called your access token, the real access token value is on AccessToken.getToken() method.

回调重定向(非 OOB)

如果您没有将 callback_url 设置为 oob,Twitter 将在使用授权令牌授权您的应用程序后重定向回您的应用程序.我已经创建了一个处理此问题的流程,因此我们需要 OAuthServlet 来为我们执行此操作.

If you didn't set your callback_url as oob, Twitter will redirect back to your application after authorizing your application with an authorized Token. I have created a process that handled this so we'll need our OAuthServlet to do this for us.

首先,我们需要在我们项目的 WEB-INF 项目下创建一个 oauth-config.xml,如下所示:

First, we'll need to create a oauth-config.xml under our project's WEB-INF project, like so:

<?xml version="1.0" encoding="UTF-8"?>
<oauth-config>
<!-- Twitter OAuth Config -->
        <oauth name="twitter" version="1">
                <consumer key="TWITTER_KEY" secret="TWITTER_SECRET" />
                <provider requestTokenUrl="https://api.twitter.com/oauth/request_token" authorizationUrl="https://api.twitter.com/oauth/authorize" accessTokenUrl="https://api.twitter.com/oauth/access_token" />
        </oauth>


        <service path="/request_token_ready" class="com.neurologic.example.TwitterOAuthService" oauth="twitter">
                <success path="/start.htm" />
        </service>
</oauth-config>

然后我们需要配置我们的 web.xml 以包含 OAuthServlet.

Then we'll need to configure our web.xml to include OAuthServlet.

<servlet>
    <description>An OAuth Servlet Controller</description>
    <display-name>OAuthServlet</display-name>
    <servlet-name>OAuthServlet</servlet-name>
    <servlet-class>com.neurologic.oauth.servlet.OAuthServlet</servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/oauth-config.xml</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>OAuthServlet</servlet-name>
    <url-pattern>/oauth/*</url-pattern>
</servlet-mapping>

现在定义一个服务.该服务将要求我们为其提供一个 RequestToken 和一个 realm(如果您愿意的话).我的完整源代码如下.在调用服务之前,我已在会话中保存了我在上面检索到的请求令牌.

And now define a Service. That service will require us to provide it a RequestToken and a realm (if you so wish). My full source code is as follows. I had saved my request token I retrieved above in a session prior to invoking the service.

/**
 * 
 */
package com.neurologic.example;

import javax.servlet.http.HttpServletRequest;

import net.oauth.signature.OAuthSignature;
import net.oauth.signature.impl.OAuthHmacSha1Signature;
import net.oauth.token.v1.AccessToken;
import net.oauth.token.v1.RequestToken;

import com.neurologic.oauth.service.impl.OAuth1Service;

/**
 * @author Buhake Sindi
 * @since 31 May 2011
 *
 */
public class TwitterOAuthService extends OAuth1Service {

    public static final String TWITTER_REQUEST_TOKEN_SESSION = "TWITTER_REQUEST_TOKEN_SESSION";
    public static final String TWITTER_ACCESS_TOKEN_SESSION = "TWITTER_ACCESS_TOKEN_SESSION";

    /* (non-Javadoc)
     * @see com.neurologic.oauth.service.impl.OAuth1Service#getOAuthSignature()
     */
    @Override
    protected OAuthSignature getOAuthSignature() {
        // TODO Auto-generated method stub
        return new OAuthHmacSha1Signature();
    }

    /* (non-Javadoc)
     * @see com.neurologic.oauth.service.impl.OAuth1Service#getRealm()
     */
    @Override
    protected String getRealm() {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.neurologic.oauth.service.impl.OAuth1Service#getRequestToken(javax.servlet.http.HttpServletRequest)
     */
    @Override
    protected RequestToken getRequestToken(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return (RequestToken) request.getSession().getAttribute(TWITTER_REQUEST_TOKEN_SESSION);
    }

    /* (non-Javadoc)
     * @see com.neurologic.oauth.service.OAuthService#saveAccessToken(javax.servlet.http.HttpServletRequest, java.lang.Object)
     */
    @Override
    public void saveAccessToken(HttpServletRequest request, AccessToken accessToken) {
        // TODO Auto-generated method stub
        request.getSession().setAttribute(TWITTER_ACCESS_TOKEN_SESSION, accessToken);
    }
}

服务中的 saveAccessToken() 方法是 Twitter 收到 Access Token 时服务调用的方法(我以 Twitter 为例,但可以随意使用任何服务提供者).

The saveAccessToken() method from the service is the method called by the service when the Access Token is received by Twitter (I'm using Twitter as an example, but feel free to use any service provider).

Servlet 通过授权我的请求令牌和检索访问令牌来处理握手,而无需我编写额外的流程代码.

The Servlet handles the handshaking from authorizing my request token and retrieving an access token without me writing extra flow code.

希望对大家有帮助!

这篇关于使用 JOAuth 进行 OAuth 1 授权,需要示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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