EzDevInfo.com

rauth

A Python library for OAuth 1.0/a, 2.0, and Ofly. Rauth — rauth 0.7.1 documentation

Reuse OAuth1 authorization tokens with rauth

I have the following implementation of a twitter client using rauth (OAuth1), based on the twitter-timeline-cli.py script in the rauth examples:

from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = {
        'user1' : ("xxx", "yyy", "2342354"), # These should be real tokens
    }

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key=TWITTER_CONSUMER_KEY,
            consumer_secret=TWITTER_CONSUMER_SECRET,
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1/')

    def authorize(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        return request_token, request_token_secret, pin

    def init_session(self, user):
        if user in self.KNOWN_USERS :
            request_token, request_token_secret, pin = self.KNOWN_USERS[user]
        else:
            request_token, request_token_secret, pin = self.authorize()
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        return session

    def list_tweets(self, user):
        session = self.init_session(user)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)

        for i, tweet in enumerate(r.json(), 1):
            handle = tweet['user']['screen_name'].encode('utf-8')
            text = tweet['text'].encode('utf-8')
            print '{0}. @{1} - {2}'.format(i, handle, text)

tc = TwitterClient()

tc.list_tweets('user1')

The idea is that, if the user is not known, he is requested to authorize the application. If, on the other hand, the user has already authorized this application, the authorization tokens (request_token, request_token_secret, pin) should be reused (normally the tokens would be in a database; for the time being, they are hard-coded in the script)

But this is not working:

Traceback (most recent call last):
  File "my-twitter-timeline-cli.py", line 56, in <module>
    tc.list_tweets('user1')
  File "my-twitter-timeline-cli.py", line 43, in list_tweets
    session = self.init_session(user)
  File "my-twitter-timeline-cli.py", line 39, in init_session
    data={'oauth_verifier': pin})
  File ".../lib/python2.7/site-packages/rauth/service.py", line 326, in get_auth_session
    **kwargs)
  File ".../lib/python2.7/site-packages/rauth/service.py", line 299, in get_access_token
    process_token_request(r, decoder, key_token, key_token_secret)
  File ".../lib/python2.7/site-packages/rauth/service.py", line 25, in process_token_request
    raise KeyError(PROCESS_TOKEN_ERROR.format(key=bad_key, raw=r.content))
KeyError: 'Decoder failed to handle oauth_token with data as returned by provider. A different decoder may be needed. Provider returned: <?xml version="1.0" encoding="UTF-8"?>\n<hash>\n  <error>Invalid / expired Token</error>\n  <request>/oauth/access_token</request>\n</hash>\n'

Is it possible to reuse OAuth1 authorization tokens?


Source: (StackOverflow)

Getting 400 from Bitbucket OAuth

from rauth import OAuth1Service

OAUTH_REQUEST = "https://bitbucket.org/!api/1.0/oauth/request_token"
OAUTH_AUTH = "https://bitbucket.org/!api/1.0/oauth/authenticate"
OAUTH_ACCESS = "https://bitbucket.org/!api/1.0/oauth/access_token"

service = OAuth1Service(
           name='test',
           consumer_key='xxxxxxxxxxxxxx',
           consumer_secret='xxxxxxxxxxxxxxxxxxxx',
           request_token_url=OAUTH_REQUEST,
           access_token_url=OAUTH_ACCESS,
           authorize_url=OAUTH_AUTH)

resp = service.get_raw_request_token()
print resp

I went on Bitbucket and generated a consumer key-pair, but the response was 400. Any idea what's going on?

I looked at the Bitbucket doc and the URL are correct.


edit

Thank you to @maxcountryman for taking his time here.

I just read his linkedlin example code:

import os
from rauth import OAuth1Service

OAUTH_REQUEST = "https://bitbucket.org/!api/1.0/oauth/request_token"
OAUTH_AUTH = "https://bitbucket.org/!api/1.0/oauth/authenticate"
OAUTH_ACCESS = "https://bitbucket.org/!api/1.0/oauth/access_token"

service = OAuth1Service(
           name='test',
           consumer_key='blah',
           consumer_secret='blah',
           request_token_url=OAUTH_REQUEST,
           access_token_url=OAUTH_ACCESS,
           authorize_url=OAUTH_AUTH)

# You can run python -m SimpleHTTPServer if you want a local callback
rtoken, rtoken_secret = service.get_request_token(params={'oauth_callback': 'http://localhost:8000'})

authorize_url = service.get_authorize_url(rtoken)
print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')
session = service.get_auth_session(rtoken,
                                   rtoken_secret,
                                   data={'oauth_verifier': pin})

reponame = raw_input('Enter the reponame: ')
new_name = raw_input('Enter a new repo name: ')
account_name = raw_input('Enter your account name: ')
url = 'https://api.bitbucket.org/1.0/repositories/%s/%s' %(account_name, reponame)
r = session.put(url, data={'name': new_name})
print r

Example:

(k)yeukhon@yeukhon-P5E-VM-DO:/tmp$ python bb2.py
Visit this URL in your browser: https://bitbucket.org/!api/1.0/oauth/authenticate?oauth_token=xxxxxxxxxxxxx
Enter PIN from browser: 216000000
Enter the reponame: newpatch
Enter a new repo name: junk-patch
Enter your account name: yeukhon
<Response [200]>

edit take additional advice from max using base_url.

OAUTH_REQUEST = "https://bitbucket.org/!api/1.0/oauth/request_token"
OAUTH_AUTH = "https://bitbucket.org/!api/1.0/oauth/authenticate"
OAUTH_ACCESS = "https://bitbucket.org/!api/1.0/oauth/access_token"

service = OAuth1Service(
           name='test',
           consumer_key='blah',
           consumer_secret='blah',
           request_token_url=OAUTH_REQUEST,
           access_token_url=OAUTH_ACCESS,
           authorize_url=OAUTH_AUTH,
           base_url='https://api.bitbucket.org/1.0/')

# You can run python -m SimpleHTTPServer if you want a local callback
rtoken, rtoken_secret = service.get_request_token(params={'oauth_callback': 'http://localhost:8000'})

authorize_url = service.get_authorize_url(rtoken)
print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')
session = service.get_auth_session(rtoken,
                                   rtoken_secret,
                                   data={'oauth_verifier': pin})

reponame = raw_input('Enter the reponame: ')
new_name = raw_input('Enter a new repo name: ')
account_name = raw_input('Enter your account name: ')
url = 'repositories/%s/%s' %(account_name, reponame)
r = session.put(url, data={'name': new_name})
print r.text
print r

Source: (StackOverflow)

Advertisements

getting the facebook access token from url in flask

I am writing an app using flask. I am using the RAuth module for OAuth. The url encoded access token that facebook is returning is formatted like www.myurl.com/authCallback#access_token=<token>.

I tried getting the raw string of the url using 'request.url', but that only returns www.myurl.com/authCallback

I also tried using a decoration of @app.route('/authCallback/<access_token>') which gives me a 404.

Is there a way to do this. Has anyone used these to libraries together before?


Source: (StackOverflow)

Multiple requests over a Rauth OAuth 1.0 session

We're using Rauth to connect to various OAuth 1 APIs. It works fine for a single request, but trying to do 2 or more requests against the given session results in 401 not authorized errors from the APIs.

Twitter API example:

import requests
from rauth import OAuth1Service
from rauth import OAuth1Session

consumer_key = {the consumer key}
consumer_secret = {the consumer secret}
access_token = {the access token}
access_token_secret = {the access token secret}

oauth_service = OAuth1Service(consumer_key = consumer_key, 
                            consumer_secret = consumer_secret)
oauth_session = oauth_service.get_session(token = (access_token, access_secret))

url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'
params = {'include_rts': 'true'}
r = oauth_session.get(url, params=params) # THIS WORKS
r = oauth_session.get(url, params=params) # THIS RETURNS 401 ERROR

This happens on both Twitter and LinkedIn APIs. How do we execute multiple requests against a single OAuth1Session object?

VERSIONS:
rauth==0.5.4
requests==1.1.0


UPDATE:

Strangely, if the params argument is not included then multiple requests can be made- but once params are included, even if it is an empty dict, we get 401s.

Example 1:

r = oauth_session.get(url) # THIS WORKS
r = oauth_session.get(url) # THIS WORKS

Example 2:

r = oauth_session.get(url, params={}) # THIS WORKS
r = oauth_session.get(url, params={}) # THIS RETURNS 401 ERROR

Source: (StackOverflow)

Using LinkedIn oauth2.0 with rauth

I am trying to connect to LinkedIn using the OAuth2Service provided by rauth. I successfully retrieve the access token. To do so, I configured a specific decoder for the json response.

json_decoder = json.loads
params = {'decoder': json_decoder}
session = linkedin.get_auth_session(data=data, **params)

But when doing the API call via r = session.get('people/~', data={"x-li-format":'json'},) the following response is coming back:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error>
  <status>401</status>
  <timestamp>1369334215190</timestamp>
  <request-id>F3SKIP4YUF</request-id>
  <error-code>0</error-code>
  <message>Unknown authorization header {Bearer AQU2HxhdXVHGG4sIWdZV7siahjVyTz0KIigEVvtMpAh...}
</message>
</error>

Is it possible that LinkedIn does not support the bearer token? If so, does rauth support other schemes?


Source: (StackOverflow)

How do you use rauth with Django?

The python lib mentioned in OAuth website rauth seems to be simple and best one to use. So, I want to use it in Django and unable to actually implement it.

Here is my issue.

# I do something like this initially
from rauth.service import OAuth2Service
from django.shortcuts import render_to_response
def page(request):
    service = OAuth2Service(
                           consumer_key = "..",
                           consumer_secret = "...",
                           .. )
    url = service.get_authorize_url(redirect_uri="http://mysite.com/redired-url")
    # this url is where the user accepts or not.
    # which redirects with authorization code.
    return HttpResponseRedirect(url)

Now, when user opens page, it directly redirects and asks user to allow or reject.. If user allows, we get authorization code at redirect-url

To get access token from authorization token,

rauth lib mentions to do so which I have to put under a different view corresponding to redirect-url

data = dict(code='foobar',
            grant_type='authorization_code',
            redirect_uri='http://example.com/')
token = service.get_access_token('POST', data=data)

The problem is with service object. I created service instance in one view, i need to use it in another view to get access token..

Where I am going wrong..? How to get it done.


Source: (StackOverflow)

rauth/flask: How to login via Twitter?

The provided example in rauth is using the PIN instead of the callback. I don't understand how this should work via web callback.

1) Minor problem:

According to twitter, if oauth_callback URL is passed in, then it should be used instead whatever entry is in the https://dev.twitter.com settings. However this doesn't seem to be true, if I dont set it to http://127.0.0.1:8080/twitter/authorized it would never get to that Url after a successful authorization.

app.add_url_rule('/twitter/login', view_func=views.twitter_login)  
app.add_url_rule('/twitter/authorized', 'twitter_authorized', view_func=views.twitter_authorized)

def twitter_login():
    request_token, request_token_secret = twitter.get_request_token()
    redirect_uri = url_for('twitter_authorized', _external=True)
    params = {'oauth_callback': redirect_uri, 'request_token':request_token}
    return redirect(twitter.get_authorize_url(**params))

2) Major problem is here:

I can see the request.args has both ['oauth_token'] and ['oauth_verifier']. But I don't understand how to use them to get the twitter session for obtaining user details such as picture and display name:

def twitter_authorized():
    tw_session = twitter.get_auth_session(request_token ??? , request_token_secret ???)
    resp = tw_session.get("account/verify_credentials.json", params={'format':'json'})    
    me = resp.json()
    user = User.get_or_create(...)

    if user:  
        login_user(user)            
    return redirect(url_for('index'))

If someone could shed some light on this, would be highly appreciated.


Source: (StackOverflow)

Unable to access LinkedIn connections using rauth library

I was trying out this Github example.

I get a 403, Access to connections denied error and it returns KeyError: '_total'.

r_network option is present. Has anyone faced this issue?

Also if you look at this Python docs page, the 'requests' library is initializing resource_owner_key, resource_owner_secret apart from the application keys. Not sure how these are getting passed from the 'rauth' library, Was wondering if that was causing this 403 error.


Source: (StackOverflow)

error using rauth in app engine (Permission denied)

I have a app engine app, using oauth and rauth, i'm trying to use Facebook, Twitter and google to login.

When i run it locally works, but in production i got this error, but only with google plus, with facebook works fine.

('Connection aborted.', error(13, 'Permission denied')) Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in call rv = self.handle_exception(request, response, e) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in call rv = self.router.dispatch(request, response) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in call return handler.dispatch() File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/handler.py", line 11, in dispatch webapp2.RequestHandler.dispatch(self) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/loginToken.py", line 69, in get ep=log.getTokenData(code) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/conect.py", line 34, in getTokenData session = self.getSession(conf,code) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/conect.py", line 61, in getSession session=conf.get_auth_session(data=self.getData(code), decoder=json.loads) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/service.py", line 556, in get_auth_session session = self.get_session(self.get_access_token(method, **kwargs)) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/service.py", line 541, in get_access_token r = self.get_raw_access_token(method, **kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/service.py", line 518, in get_raw_access_token **kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/session.py", line 358, in request return super(OAuth2Session, self).request(method, url, **req_kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/requests/sessions.py", line 457, in request resp = self.send(prep, **send_kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/requests/sessions.py", line 569, in send r = adapter.send(request, **kwargs) File "/base/data/home/apps/s~app-getwell/login:1.379942143707124638/code/oauth/rauth/requests/adapters.py", line 407, in send raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))

I have the billing enabled, and in the yaml have added the ssl library (latests)

This is the code with wich i make the oauth calls

class login():    
    def __init__(self,tipo=tipoConexion.Google, redirect_uri =  'http://map.getwell.care/'):
        self.__tipo=tipo        
        self.config=config.data(redirect_uri)        

    def getAuthorizationURL(self):
        conf=self.getConfig()
        params=self.getParams()
        url = conf.get_authorize_url(**params)
        return url

    def getTokenData(self, code):
        ''' Get the data that i need from the provider '''
        conf=self.getConfig()
        session = self.getSession(conf,code)
        tokenizerConcreto=JsonReader.factory(self.__tipo,session)
        email=tokenizerConcreto.getEmail()[0]
        urlPic=tokenizerConcreto.getPicture()[0]
        logueado=not tokenizerConcreto.getEmail()[1]
        return logueado, urlPic, email

    def getParams(self):
        params=None
        if self.__tipo==tipoConexion.Google:            
            params = self.config.GooglePlusScope
        if self.__tipo==tipoConexion.Facebook:
            params = self.config.FacebookScope
        return params

    def getConfig(self):
        conf=self.config.googlePlus
        if self.__tipo==tipoConexion.Facebook:
            conf=self.config.facebook
        if self.__tipo==tipoConexion.Twitter:
            conf=self.config.twitter
        return conf

        def getSession(self,conf, code):
            session=None
            if self.__tipo==tipoConexion.Google:
                session=conf.get_auth_session(data=self.getData(code), decoder=json.loads)
            else:
                session=conf.get_auth_session(data=self.getData(code))
            return session        

    def getData(self,code):
        data=None
        if self.__tipo==tipoConexion.Google:
            data={
                 'code' : code,
                 'redirect_uri': self.config.redirect_uri,
                 'grant_type':'authorization_code'
             }#
            logging.info("GetWell: Data previo al error: %s" % data)
        if self.__tipo==tipoConexion.Facebook:
             data={
                 'code' : code,
                 'redirect_uri': self.config.redirect_uri,                  
             }    
        if self.__tipo==tipoConexion.Twitter:
            raise NotImplementedError
        return data

and this is the code when i got the secrets keys

class tipoConexion():
    Google=0
    Facebook=1
    Twitter=2

class data(object):
    def __init__(self, url =  'http://map.getwell.care/'):
        self.redirect_uri=url

    def getURL(self):
        return self.redirect_uri

    @property
    def twitter(self):
        return OAuth1Service(
            consumer_key='imnotatwitterman',
            consumer_secret='ilovevine',
            name='twitter',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            request_token_url='https://api.twitter.com/oauth/request_token',
            base_url='https://api.twitter.com/1/')

    @property
    def facebook(self):
        return OAuth2Service(
            client_id='someID',
            client_secret='MyDarkSecretInFacebook',
            name='facebook',
            authorize_url='https://graph.facebook.com/oauth/authorize',
            access_token_url='https://graph.facebook.com/oauth/access_token',
            base_url='https://graph.facebook.com/')

    @property
    def FacebookScope(self):
        return {
                'scope': 'public_profile,email',
                'response_type': 'code',
                'redirect_uri': self.getURL()
            }

    @property
    def googlePlus(self):
        return OAuth2Service(
            client_id='ThisCouldBeMyID.apps.googleusercontent.com',
            client_secret='Idonthaveanysecrets',
            name='googlePlus',
            authorize_url='https://accounts.google.com/o/oauth2/auth',
            access_token_url='https://accounts.google.com/o/oauth2/token',
            base_url='https://accounts.google.com/o/oauth2/auth')

    @property
    def GooglePlusScope(self):
        return  {
                'scope': 'https://www.googleapis.com/auth/plus.profile.emails.read',
                'response_type': 'code',
                 'redirect_uri': self.getURL()
                }

as i said the most strange is that works fine with facebook, but, fail with google plus (i doble check the client_id and the client_secret and are correct) if it was a problem with the sockets facebook would have to fail too

ps. I copy the rauth files in my project and the request files inside the rauth folder


Source: (StackOverflow)

need some help authenticating to github API with python

I have followed this tutorial to authenticate to the Github API using Python.

Though, for me it doesn't work, when I go to localhost:5000 I'm getting a "this webpage is not available" message. it just says that it's started at localhost:5000 and returning no errors after I executed python github.py. My directory/file tree looks like:

-templates
 -login.html
 -about.html
-github.py
-github.db

message after executing: python github.py

 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

What did I do wrong and is there any way I can make this work correctly?

Or, are there any alternatives on authenticating to the Github API using Python? Couldn't find any, but are there?


Source: (StackOverflow)

Flask Social Authentication Class Issue

I am working off of a Miguel Grinberg tutorial on social authentication.

On the homepage template I have this code, and I removed the twitter portion from the tutorial:

    <h2>I don't know you!</h2>
    <p><a rel='nofollow' href="{{ url_for('oauth_authorize', provider='facebook') }}">Login with Facebook</a></p>
{% endif %}

So when you click that link, you pass Facebook as the provider through this view function:

@app.route('/authorize/<provider>')
def oauth_authorize(provider):
    if not current_user.is_anonymous():
        return redirect(url_for('index'))
    oauth = OAuthSignIn.get_provider(provider)
    return oauth.authorize()

Now, in a different file, oauth.py, I have the following and my issue is this. I keep getting an error when I click the Facebook link UNLESS the TwitterSignIn class is removed. I guess I am curious as to why the TwitterSignIn class needs to be removed for this to work, because no data is being passed to it, right? Even if Facebook wasn't the only option, why would clicking the Facebook sign-in link pass any data to the TwitterSignIn class?

from rauth import OAuth1Service, OAuth2Service
from flask import current_app, url_for, request, redirect, session


class OAuthSignIn(object):
    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
        self.consumer_id = credentials['id']
        self.consumer_secret = credentials['secret']

    def authorize(self):
        pass

    def callback(self):
        pass

    def get_callback_url(self):
        return url_for('oauth_callback', provider=self.provider_name,
                       _external=True)

    @classmethod
    def get_provider(self, provider_name):
        if self.providers is None:
            self.providers = {}
            for provider_class in self.__subclasses__():
                provider = provider_class()
                self.providers[provider.provider_name] = provider
        return self.providers[provider_name]


class FacebookSignIn(OAuthSignIn):
    def __init__(self):
        super(FacebookSignIn, self).__init__('facebook')
        self.service = OAuth2Service(
            name='facebook',
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            authorize_url='https://graph.facebook.com/oauth/authorize',
            access_token_url='https://graph.facebook.com/oauth/access_token',
            base_url='https://graph.facebook.com/'
        )

    def authorize(self):
        return redirect(self.service.get_authorize_url(
            scope='email',
            response_type='code',
            redirect_uri=self.get_callback_url())
        )

    def callback(self):
        if 'code' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            data={'code': request.args['code'],
                  'grant_type': 'authorization_code',
                  'redirect_uri': self.get_callback_url()}
        )
        me = oauth_session.get('me').json()
        return (
            'facebook$' + me['id'],
            me.get('email').split('@')[0],  # Facebook does not provide
                                            # username, so the email's user
                                            # is used instead
            me.get('email')
        )


class TwitterSignIn(OAuthSignIn):
    def __init__(self):
        super(TwitterSignIn, self).__init__('twitter')
        self.service = OAuth1Service(
            name='twitter',
            consumer_key=self.consumer_id,
            consumer_secret=self.consumer_secret,
            request_token_url='https://api.twitter.com/oauth/request_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            access_token_url='https://api.twitter.com/oauth/access_token',
            base_url='https://api.twitter.com/1.1/'
        )

    def authorize(self):
        request_token = self.service.get_request_token(
            params={'oauth_callback': self.get_callback_url()}
        )
        session['request_token'] = request_token
        return redirect(self.service.get_authorize_url(request_token[0]))

    def callback(self):
        request_token = session.pop('request_token')
        if 'oauth_verifier' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            request_token[0],
            request_token[1],
            data={'oauth_verifier': request.args['oauth_verifier']}
        )
        me = oauth_session.get('account/verify_credentials.json').json()
        social_id = 'twitter$' + str(me.get('id'))
        username = me.get('screen_name')
        return social_id, username, None   # Twitter does not provide email

Some additional information-

The specific error is this:

File "/Users/metersky/code/mylastapt/app/oauth.py", line 29, in get_provider
provider = provider_class()
File "/Users/metersky/code/mylastapt/app/oauth.py", line 73, in __init__
super(TwitterSignIn, self).__init__('twitter')
File "/Users/metersky/code/mylastapt/app/oauth.py", line 10, in __init__
credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
KeyError: 'twitter'

And this is where the I think the issue might be happening:

app.config['OAUTH_CREDENTIALS'] = {
    'facebook': {
        'id': 'XXX',
        'secret': 'XXXX'
    }
}

Source: (StackOverflow)

Connecting to LinkedIn API with rauth

I'm trying to get a website to connect to LinkedIn, I know I have to use OAuth tokens to connect to it, and I have seen the examples on the LinkedIn developer site, however, they all use the OAuth2 library and the site that I'm working with uses the rauth library, which seems to skip a few of the steps. It already has Twitter integrated, so I'll include the code below in case anyone doesn't quite understand what I mean.

twitter.py:

import json

from django.http import HttpResponse
from django.conf import settings
from rauth.service import OAuth1Service

def twitter(request, username):
    twitter = OAuth1Service(
    name='twitter',
    consumer_key=settings.TWITTER_CONSUMER_KEY,
    consumer_secret=settings.TWITTER_CONSUMER_SECRET,
    request_token_url=settings.TWITTER_API_URL + 'oauth/request_token',
    access_token_url=settings.TWITTER_API_URL + 'oauth/access_token',
    authorize_url=settings.TWITTER_API_URL + 'oauth/authorize',
    header_auth=True)

url = '{0}1/statuses/user_timeline.json?include_rts=false' \
    '&exclude_replies=true&count=50&screen_name={1}'.format(
        settings.TWITTER_API_URL, username)

r = twitter.request('GET', url, access_token=settings.TWITTER_USER_KEY,
                    access_token_secret=settings.TWITTER_USER_SECRET)

return HttpResponse(content=json.dumps(r.response.json),
                    status=r.response.status_code,
                    content_type=r.response.headers['content-type'])

Since it isn't commented, I think it's makes a request to the url which returns the user's timeline when sent, but how come there's no request token creation OR access token creation? It has the TWITTER_USER_KEY and TWITTER_USER_SECRET, but the rauth documentation says you should call explicit methods to get the tokens. What am I missing here?

EDIT: I'd quite like to just use the rauth library, and not meddle around with other libraries too.


Source: (StackOverflow)

Properly creating OAuth2Service with Rauth and Django

I am using rauth to authentication against stripe connect. In doing so I am needing to instantiate a OAuth2Service for use in multiple views. Right now my views file looks a lot like this (and works), but this just feels wrong:

from rauth.service import Oauth2Service

service = OAuth2Service(
    name = 'stripe',
    client_id = 'my_client_id',
    client_secret = 'my_secret',
    authorize_url = 'auth_url',
    access_token_url = 'stripe_access_token_url',
    base_url = 'stripe_api_url',
)

def stripe_auth(request):
    params = {'response_type': 'code'}
    url = service.get_authorize_url(**params)
    return HttpResponseRedirect(url)

def stripe_callback(request):
    code = request.GET['code']
    data = {
        'grant_type': 'authorization_code',
        'code': code
    }
    resp = service.get_raw_access_token(method='POST', data=data)
    ... rest of view code ...

My problem is that I feel that placing the "service" variable outside of the views is somehow wrong, but I am not sure the way I really should handle this. Should I split it out into a separate module, place it in the settings file, create a decorator? I am not real sure.

Any advice is greatly appreciated.


Source: (StackOverflow)

Python rauth connection to linkedin

I have recently taken over support for an app that uses rauth to connect to linkedin. The code that is failing is:

    self.linkedin= OAuth1Service(                                                     
        name='linkedin',                                                          
        consumer_key=self._consumer_key,                                              
        consumer_secret=self._consumer_secret,                                       
        request_token_url=self.request_token_url,      
        access_token_url=self.access_token_url,        
        authorize_url=self.authorize_url)          

    self.request_token, self.request_token_secret = \
                        self.linkedin.get_request_token(method='GET',
                        oauth_callback=self.callback_url)

The owner of the app says this used to work but now we're getting:

TypeError: request() got an unexpected keyword argument 'oauth_callback'

Can you point me to some doc/examples that would help me re-architect this?

-Jim


Source: (StackOverflow)

Incorrect URL without an access token for facebook login using rauth

I have the code from rauth site:

https://github.com/litl/rauth/blob/master/examples/facebook-cli.py

(The code can be found at the end of this post for reference)

running the program in the command line will open a firefox window and the following message is shown from facebook site:

Success
SECURITY WARNING: Please treat the URL above as you would your password and do not     share it with anyone.

when the facebook is logged in beforehand. Even if not logged in, the facebook login window opens up and after logging in using username/password the above message is shown in firefox window.

Now the URL generated in the address bar:

https://www.facebook.com/connect/blank.html#_=_

Which is obviously an incorrect one and it gives exception from the subsequent python code.

Now how can I debug what the problem is?

Thanks

PS:

from rauth.service import OAuth2Service

import re
import webbrowser

# Get a real consumer key & secret from:
# https://developers.facebook.com/apps

facebook = OAuth2Service(
    client_id='xxxxxxx',
    client_secret='yyyyyyy',
    name='facebook',
    authorize_url='https://graph.facebook.com/oauth/authorize',
    access_token_url='https://graph.facebook.com/oauth/access_token',
    base_url='https://graph.facebook.com/')

redirect_uri = 'https://www.facebook.com/connect/login_success.html'

params = {'scope': 'read_stream',
      'response_type': 'token',
      'redirect_uri': redirect_uri}

authorize_url = facebook.get_authorize_url(**params)

print 'Visit this URL in your browser: ' + authorize_url
webbrowser.open(authorize_url);

url_with_code = raw_input('Copy URL from your browser\'s address bar: ')
access_token = re.search('\#access_token=([^&]*)', url_with_code).group(1)
session = facebook.get_session(access_token)

user = session.get('me').json()

print 'currently logged in as: ' + user['link']

Source: (StackOverflow)