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

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

问题描述

由于我在LinkedIn / Twitter上看到过如何进行OAuth 1 3-legged或2-legged授权的问题,我想我会发布一个例子,告诉我如何用 JOAuth

解决方案

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



首先,您将需要Twitter中的两件事,您需要将您的申请注册到Twitter并获得申请:




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

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



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



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

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

哦,是的,我们需要 callback_url

  private static final String CALLBACK_URL =oob; 

我会解释 oob (Out-以后,我们需要创建一个为我们执行OAuth授权的消费者:

 私有OAuth1Consumer使用者=新OAuth1Consumer(API_KEY,API_SECRET,新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)令牌URL,授权令牌URL,访问令牌URL)。



现在,让乐趣开始吧:



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



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

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

第一个参数是 realm ,这是null (因为Twitter并没有真正使用它),然后是 callback_url ,以及签名方法。



3有效OAuth签名方法:




  • PLAINTEXT(按原样发送,以纯文本格式),类 OAuthPlainTextSignature

  • HMAC-SHA1,类 OAuthHmacSha1Signature

  • RSA-SHA1, class OAuthRsaSha1Signature



Twitter使用HMAC-SHA1,请参考文档向其他提供商执行OAuth。



现在我们有一个未经授权的请求令牌,让我们授权它。



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



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

  String url = consu mer.createOAuthUserAuthorizationUrl(requestToken,null); 

(第二个参数是 null 因为我们没有其他HTTP参数可以发送,但如果你这样做,创建一个 Map< String,String> 属性,填充它们并在方法调用中将其分块:) )



现在我们有了URL,将URL丢到浏览器,授权应用程序,这里是 callback_url 进来:



带外(OOB)授权



OOB授权用于无法执行HTTP重定向但仍希望请求访问令牌的应用程序。 Twitter声明使用PIN而不是HTTP重定向。该PIN(在授权Twitter应用程序后显示)由Twitter显示为浏览器上的图像。有关详细信息,请参阅 Twitter OAuth API文档



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

  String twitterPin =; //无论Twitter显示什么
AccessToken accessToken = example.requestAccessToken(new AuthorizedToken(requestToken.getToken(),twitterPin),requestToken);

我们走了。



调用访问令牌后,实际访问令牌值为 AccessToken.getToken()方法。



回调重定向(非OOB)



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



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

 <?xml version =1.0encoding =UTF-8?> 
< oauth-config>
<! - Twitter OAuth配置 - >
< oauth name =twitterversion =1>
< consumer key =TWITTER_KEYsecret =TWITTER_SECRET/>
< provider requestTokenUrl =https://api.twitter.com/oauth/request_tokenauthorizationUrl =https://api.twitter.com/oauth/authorizeaccessTokenUrl =https:// api。 twitter.com/oauth/access_token/>
< / oauth>


< service path =/ request_token_readyclass =com.neurologic.example.TwitterOAuthServiceoauth =twitter>
< success path =/ start.htm/>
< / service>
< / oauth-config>

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

 < servlet> 
< description> OAuth Servlet控制器< / 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 领域(如果您愿意)。我的完整源代码如下。我在调用服务之前已经在会话中保存了我上面检索到的请求令牌。

  / ** 
*
* /
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 2011年5月31日
*
* /
公共类TwitterOAuthService扩展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;

/ *(非Javadoc)
* @see com.neurologic.oauth.service.impl.OAuth1Service#getOAuthSignature()
* /
@Override
protected OAuthSignature getOAuthSignature(){
// TODO自动生成的方法stub
返回新的OAuthHmacSha1Signature();
}

/ *(非Javadoc)
* @see com.neurologic.oauth.service.impl.OAuth1Service#getRealm()
* /
@Override
protected String getRealm(){
// TODO自动生成的方法stub
返回null;
}

/ *(非Javadoc)
* @see com.neurologic.oauth.service.impl.OAuth1Service #getRequestToken(javax.servlet.http.HttpServletRequest)
* /
@Override
protected RequestToken getRequestToken(HttpServletRequest request){
// TODO自动生成的方法stub
return(RequestToken)request.getSession()。getAttribute (TWITTER_REQUEST_TOKEN_SESSION);
}

/ *(非Javadoc)
* @see com.neurologic.oauth.service.OAuthService#saveAccessToken(javax.servlet.http.HttpServletRequest,java.lang .Object)
* /
@Override
public void saveAccessToken(HttpServletRequest request,AccessToken accessToken){
// TODO自动生成的方法stub
request.getSession( ).setAttribute(TWITTER_ACCESS_TOKEN_SESSION,accessToken);
}
}

saveAccessToken()来自服务的方法是当Twitter接收到访问令牌时服务调用的方法(我使用Twitter作为示例,但随意使用任何服务提供商)。



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



我希望这对每个人都有帮助!


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.

解决方案

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

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

  • API Key (which OAuth calls consumer key)
  • API Secret (which OAuth calls it consumer secret).

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

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";

Oh yes, we need a callback_url:

private static final String CALLBACK_URL = "oob";

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

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"));

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).

Now, let the fun begin:

Requesting a (unauthorized) request Token:

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

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

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

There are 3 valid OAuth Signature method:

  • PLAINTEXT (send as is, in plaintext), class OAuthPlainTextSignature.
  • HMAC-SHA1, class OAuthHmacSha1Signature.
  • RSA-SHA1, class OAuthRsaSha1Signature.

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.

Authorizing a (unauthorized) request Token:

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

(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 :))

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

Out-Of-Band (OOB) Authorization

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.

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

And here we go.

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

Callback Redirection (Non OOB)

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.

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>

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>

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

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).

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

I hope this helps everyone!

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

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