A Python library for OAuth 1.0/a, 2.0, and Ofly.

Related tags

Authentication rauth
Overview

Rauth

A simple Python OAuth 1.0/a, OAuth 2.0, and Ofly consumer library built on top of Requests.

build status

Features

  • Supports OAuth 1.0/a, 2.0 and Ofly
  • Service wrappers for convenient connection initialization
  • Authenticated session objects providing nifty things like keep-alive
  • Well tested (100% coverage)
  • Built on Requests (v1.x)

Installation

To install:

$ pip install rauth

Or if you must:

$ easy_install rauth

Example Usage

Let's get a user's Twitter timeline. Start by creating a service container object:

from rauth import OAuth1Service

# Get a real consumer key & secret from https://dev.twitter.com/apps/new
twitter = OAuth1Service(
    name='twitter',
    consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',
    consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',
    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.1/')

Then get an OAuth 1.0 request token:

request_token, request_token_secret = twitter.get_request_token()

Go through the authentication flow. Since our example is a simple console application, Twitter will give you a PIN to enter.

authorize_url = twitter.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')  # `input` if using Python 3!

Exchange the authorized request token for an authenticated OAuth1Session:

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
                                   data={'oauth_verifier': pin})

And now we can fetch our Twitter timeline!

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']
    text = tweet['text']
    print(u'{0}. @{1} - {2}'.format(i, handle, text))

Here's the full example: examples/twitter-timeline-cli.py.

Documentation

The Sphinx-compiled documentation is available here: http://readthedocs.org/docs/rauth/en/latest/

Contribution

Anyone who would like to contribute to the project is more than welcome. Basically there's just a few steps to getting started:

  1. Fork this repo
  2. Make your changes and write a test for them
  3. Add yourself to the AUTHORS file and submit a pull request!

Note: Before you make a pull request, please run make check. If your code passes then you should be good to go! Requirements for running tests are in requirements-dev@<python-version>.txt. You may also want to run tox to ensure that nothing broke in other supported environments, e.g. Python 3.

Copyright and License

Rauth is Copyright (c) 2013 litl, LLC and licensed under the MIT license. See the LICENSE file for full details.

Comments
  • Upgraded to 0.5.3 indicates

    Upgraded to 0.5.3 indicates "Multiple client authentications found" error

    I had the 0.5.2 version and I just upgraded to 0.5.3. After the update when I run my same code that was working 2 mins ago, is now producing "Multiple client authentications found" error and wouldn't let me get the access code anymore.

    Help!!

    opened by musabbir-khan 45
  • Python3 compat

    Python3 compat

    These patches should make it possible to use rauth with python3 without breaking python2 support.

    Not all unittests are working yet for python3. Most importantly not the unicode ones as I have to comment these out as the u'' stuff is a syntax error in 3.

    opened by keis 37
  • Python 3 changes

    Python 3 changes

    This passes tests locally on 2.6, 2.7, 3.3 and pypy 2.7 as single-source. However, that doesn't mean it's doing the right thing: unit tests should probably change to reflect your decisions on what the API is meant to do with string types. Also, I am not sure whether you want to try to support 3.2 or 3.1 as well. So at the moment this is meant pretty much to highlight what would be involved in a port based on master.

    opened by sashahart 21
  • OAuth1Session request wrapper eats some POST data

    OAuth1Session request wrapper eats some POST data

    From #66. The issue seems to be when sending a POST request with JSON encoded data, which gets wrongly parsed by parse_qsl() in session.py.

    The result is that data = {'category_id': '8'} gets transformed to category_id=8 in the POST body and json.dumps( {'category_id': '8'} ) gets completely lost ({} or None depending on Requests version)

    Removing session.py lines 142,143 fixed the issue, maybe it should to check the Content-Type?

    opened by nyov 18
  • How to upload a file to server with rauth session?

    How to upload a file to server with rauth session?

    I can use code like this to upload file to server:

    import requests
    files = {'file': open(filename, 'rb')}
    requests.post(upload_url, files = files)
    

    I see in the document that the session has same interface with requests, but when I try the code below:

    session.post(upload_url, files = files)
    

    it throws an exception: Traceback (most recent call last): File "./TudouSdk.py", line 177, in t.upload('/home/yangyu/Downloads/Screencast.mp4', 'emacs', '', 'emacs', '21') File "./TudouSdk.py", line 170, in upload session.post(upload_url, files = files) File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 377, in post return self.request('POST', url, data=data, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rauth/session.py", line 171, in request req_kwargs) File "/usr/local/lib/python2.7/dist-packages/rauth/oauth.py", line 134, in sign self._normalize_request_parameters(oauth_params, req_kwargs) File "/usr/local/lib/python2.7/dist-packages/rauth/oauth.py", line 77, in _normalize_request_parameters for k, v in data.items(): AttributeError: 'NoneType' object has no attribute 'items'

    what's wrong with this code?

    opened by yuyang0 16
  • Github example fails with an exception

    Github example fails with an exception

    When I run the Github example I get the following traceback:

    Traceback (most recent call last):
      File ".\test.py", line 29, in <module>
        access_token=access_token).content
      File "C:\Users\user\github-api-proxy\lib\site-packages\rauth\service.py", line 57, in get
        return self.request('GET', url, **kwargs)
      File "C:\Users\user\github-api-proxy\lib\site-packages\rauth\service.py", line 399, in request
        response = self.session.request(method, uri, **kwargs)
    TypeError: request() got an unexpected keyword argument 'access_token'
    

    This looks like it shouldn't happen. I'm running Python 2.7 on windows.

    opened by thedrow 15
  • Allow requests 1.2.0 or unforce the version

    Allow requests 1.2.0 or unforce the version

    For some reasons the requests version is forced to 1.1.0 and I need to use requests 1.2.0.

    It would be nice if the version is not forced at all, or in a more permissive way (ie >= 1.1.0).

    Thanks,

    Christophe

    opened by cdevienne 14
  • A change to throw actual exceptions

    A change to throw actual exceptions

    When we're doing OAuth and the response code isn't 200OK, why shouldn't we return a proper exception to the client? Without doing this, we have to parse client response, and it may not be something reasonable.

    I'd make a test case, but that would require a working web server which returns bad responses.

    opened by alertedsnake 13
  • Using rauth for twitter Oauth1 get_raw_access_token and get_auth_session

    Using rauth for twitter Oauth1 get_raw_access_token and get_auth_session

    Hey guys. Really great module. its a shame twitter cannot move to oauth2. Anyway, I'm using rauth for twitters Oauth1Service client. I keep getting a 401 on get_raw_access_token and when i try using get_auth_session and OAuth request: Invalid oauth_verifier parameter. i followed the docs as mentioned and do not seem to be doing out of the ordinary. I even tried explicitly passing the request method as 'GET'

        twitter = OAuth1Service(
                consumer_key='somethingconsumerkey',
                consumer_secret='somethingsecret',
                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/')
        request_token, request_token_secret = twitter.get_request_token()
        authorize_url = twitter.get_authorize_url(request_token)
        twitter.get_access_token(request_token, request_token_secret, method='GET')
         # or 
        twitter.get_raw_access_token(request_token, request_token_secret)
        # or 
        twitter.get_auth_session(request_token, request_token_secret)
    
    opened by jmgamboa 12
  • Keep getting 'client unauthorized' error [oauth2, linkedin]...

    Keep getting 'client unauthorized' error [oauth2, linkedin]...

    Hey,

    I want to use linkedin with oauth2, and I keep getting a 'client unauthorized' error... There's no example code for LinkedIn using oauth2, so I'm using the github example as reference, but there's still something wrong... /:

    This is what I'm doing:

    • I initialize the service:
        from rauth import *
    
        linkedin = OAuth2Service(
            client_id           = settings.LINKEDIN_TOKEN,
            client_secret       = settings.LINKEDIN_SECRET,
            name                = "linkedin",
            authorize_url       = "https://www.linkedin.com/uas/oauth2/authorization",
            access_token_url    = "https://www.linkedin.com/uas/oauth2/accessToken",
            base_url            = "https://api.linkedin.com/v1/"
    )
    
    • Create the auth_url, and send the user to authenticate himself.
    params = {
            'response_type'     : "code",
            'scope'             : "r_fullprofile r_emailaddress r_network",
            'state'             : "fasdfsadfadsfsdaf",
            'redirect_uri'      : "http://127.0.0.1:5000/portal/linkedin/authorization_code"
        }
        request_auth_code_url = linkedin.get_authorize_url(**params)
    
    • On the redirect url I parse out the auth_code, and request a new session
    authorization_code  = request.GET.get('code', '')
    data = {
            'grant_type'    : "authorization_code",
            'code'          : authorization_code,
            'redirect_uri'  : "http://127.0.0.1:5000/portal/linkedin/authorization_code/"
        }
    session = linkedin.get_auth_session(data = data)
    
    • And this is what I get....
    {
            "error" : "unauthorized_client",
            "error_description" : "the client is not authorized"
    }
    

    Please if anyone can post a working example of oauth2 with linkedin, or simple show me where my mistake it, it would really help me...

    Thanks, Alex.

    opened by A-Zak 12
  • Pickling OAuth1Service

    Pickling OAuth1Service

    Perhaps I'm missing some fundamental part of rauth (or perhaps oauth...) however I don't seem to be able to pickle OAuth1Service for later use.

    Is there a way of 'reusing' the session created using OAuth1Service.get_auth_session?

    Essentially I'd like to pickle the oauth session so I can reuse it across short lived http requests.

    As it seems rather unlikely that I'd be the first person wanting to do this, perhaps I've missed it in the docs or it isn't documented?

    opened by alexhayes 12
  • oauth.py causes NoneType Attribute Error When JSON is set but DATA is not.

    oauth.py causes NoneType Attribute Error When JSON is set but DATA is not.

    https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/oauth.py#L69

    It causes a problem when working with JSON requests. data and json args are optional and if the data is not set, this gives an attribute error.

    opened by brngylni 0
  • I've a problem......

    I've a problem......

    how to solve this.....??? (I attached traceback & source code)

    
    service=rauth.OAuth2Service(client_id=client_id,client_secret=secret,base_url="https://api.crowdstrike.com/")
    
    tr=""
    data={"token": f"{tr}"}
    def get_access_token(service):
            session = service.get_auth_session(data=data, decoder=json.loads)
            access_token = session.access_token
            tr=access_token
    
    
    
    
    session = service.get_auth_session(data=data, decoder=json.loads)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\service.py", line 556, in get_auth_session
        session = self.get_session(self.get_access_token(method, **kwargs))
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\service.py", line 541, in get_access_token
        r = self.get_raw_access_token(method, **kwargs)
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\service.py", line 516, in get_raw_access_token
        self.access_token_response = session.request(method,
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\session.py", line 345, in request
        url = self._set_url(url)
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\session.py", line 40, in _set_url
        not absolute_url(url):
      File "C:\Users\netanelst\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\rauth\utils.py", line 20, in absolute_url
        return url.startswith(('http://', 'https://'))
    AttributeError: 'NoneType' object has no attribute 'startswith'
    

    thanks Netanel

    opened by NSH531 0
  • get_auth_session  JSONDecodeError

    get_auth_session JSONDecodeError

    Is there any other way to deal with errors happening inside the get_auth_session decoding? Currently this is my code:

      try:
          session = service.get_auth_session(data=data, decoder=json.loads)
      except JSONDecodeError as e:
          print("handle error")
    
    
    opened by Lawrencedsp 0
  • docs: fix simple typo, initilize -> initialize

    docs: fix simple typo, initilize -> initialize

    There is a small typo in rauth/service.py.

    Should read initialize rather than initilize.

    Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

    opened by timgates42 0
  • test_oauth.OAuthTestRsaSha1Case throws errors with PyCryptodome

    test_oauth.OAuthTestRsaSha1Case throws errors with PyCryptodome

    When the Crypto package dependency is met with PyCryptodome instead of PyCrypto, rauth.oauth.RsaSha1Signature raises AttributeError because the internal implementation details differ in Crypto.PublicKey.RSA.

    ======================================================================
    ======================================================================
    ERROR: test_rsasha1_badargument (test_oauth.OAuthTestRsaSha1Case)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/home/neirbowj/src/github/rauth/tests/test_oauth.py", line 214, in test_rsasha1_badargument
        self.req_kwargs)
      File "/usr/local/lib/python2.7/unittest/case.py", line 473, in assertRaises
        callableObj(*args, **kwargs)
      File "/home/neirbowj/src/github/rauth/rauth/oauth.py", line 211, in sign
        if not isinstance(consumer_secret, self.RSA._RSAobj):
    AttributeError: 'module' object has no attribute '_RSAobj'
    
    ======================================================================
    ERROR: test_rsasha1_signature (test_oauth.OAuthTestRsaSha1Case)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/home/neirbowj/src/github/rauth/tests/test_oauth.py", line 199, in test_rsasha1_signature
        self.req_kwargs)
      File "/home/neirbowj/src/github/rauth/rauth/oauth.py", line 211, in sign
        if not isinstance(consumer_secret, self.RSA._RSAobj):
    AttributeError: 'module' object has no attribute '_RSAobj'
    
    
    opened by neirbowj 1
Owner
litl
Check out out Room for More (https://roomformore.com/) and Imagefly (http://imagefly.io/)
litl
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

Authlib The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included. Authlib is compatible with Python2.

Hsiaoming Yang 2.3k Feb 17, 2021
This is a Python library for accessing resources protected by OAuth 2.0.

This is a client library for accessing resources protected by OAuth 2.0. Note: oauth2client is now deprecated. No more features will be added to the l

Google APIs 787 Dec 13, 2022
Python library for generating a Mastercard API compliant OAuth signature.

oauth1-signer-python Table of Contents Overview Compatibility References Usage Prerequisites Adding the Library to Your Project Importing the Code Loa

null 23 Aug 1, 2022
Toolkit for Pyramid, a Pylons Project, to add Authentication and Authorization using Velruse (OAuth) and/or a local database, CSRF, ReCaptcha, Sessions, Flash messages and I18N

Apex Authentication, Form Library, I18N/L10N, Flash Message Template (not associated with Pyramid, a Pylons project) Uses alchemy Authentication Authe

null 95 Nov 28, 2022
A fully tested, abstract interface to creating OAuth clients and servers.

Note: This library implements OAuth 1.0 and not OAuth 2.0. Overview python-oauth2 is a python oauth library fully compatible with python versions: 2.6

Joe Stump 3k Jan 2, 2023
Doing the OAuth dance with style using Flask, requests, and oauthlib.

Flask-Dance Doing the OAuth dance with style using Flask, requests, and oauthlib. Currently, only OAuth consumers are supported, but this project coul

David Baumgold 915 Dec 28, 2022
Doing the OAuth dance with style using Flask, requests, and oauthlib.

Flask-Dance Doing the OAuth dance with style using Flask, requests, and oauthlib. Currently, only OAuth consumers are supported, but this project coul

David Baumgold 799 Feb 17, 2021
Doing the OAuth dance with style using Flask, requests, and oauthlib.

Flask-Dance Doing the OAuth dance with style using Flask, requests, and oauthlib. Currently, only OAuth consumers are supported, but this project coul

David Baumgold 802 Feb 22, 2021
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 2, 2023
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 1, 2023
Phishing Abusing Microsoft 365 OAuth Authorization Flow

Microsoft365_devicePhish Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack This is a simple proof-of-concept script that allows an at

bigb0ss 11 Dec 11, 2022
Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack

Microsoft365_devicePhish Abusing Microsoft 365 OAuth Authorization Flow for Phishing Attack This is a simple proof-of-concept script that allows an at

Optiv Security 76 Jan 2, 2023
Local server that gives you your OAuth 2.0 tokens needed to interact with the Conta Azul's API

What's this? This is a django project meant to be run locally that gives you your OAuth 2.0 tokens needed to interact with Conta Azul's API Prerequisi

Fábio David Freitas 3 Apr 13, 2022
A module making it easier to manage Discord oAuth with Quart

quart_discord A module making it easier to manage Discord oAuth with Quart Install pip install git+https://github.com/xelA/quart_discord@master How to

null 5 Oct 27, 2022
Plotly Dash plugin to allow authentication through 3rd party OAuth providers.

dash-auth-external Integrate your dashboards with 3rd parties and external OAuth providers. Overview Do you want to build a Plotly Dash app which pull

James Holcombe 15 Dec 11, 2022
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
Imia is an authentication library for Starlette and FastAPI (python 3.8+).

Imia Imia (belarussian for "a name") is an authentication library for Starlette and FastAPI (python 3.8+). Production status The library is considered

Alex Oleshkevich 91 Nov 24, 2022
A Python library to create and validate authentication tokens

handshake A Python library to create and validate authentication tokens. handshake is used to generate and validate arbitrary authentication tokens th

null 0 Apr 26, 2022
Google Auth Python Library

Google Auth Python Library This library simplifies using Google's various server-to-server authentication mechanisms to access Google APIs. Installing

Google APIs 598 Jan 7, 2023