python-oauth2 is a framework that aims at making it easy to provide authentication via OAuth 2.0 within an application stack.
Example Authorization server:
from wsgiref.simple_server import make_server
import oauth2
import oauth2.grant
import oauth2.error
import oauth2.store
import oauth2.tokengenerator
import oauth2.web
# Create a SiteAdapter to interact with the user.
# This can be used to display confirmation dialogs and the like.
class ExampleSiteAdapter(oauth2.web.SiteAdapter):
def authenticate(self, request, environ, scopes):
if request.post_param("confirm") == "1":
return {}
raise oauth2.error.UserNotAuthenticated
def render_auth_page(self, request, response, environ, scopes):
response.body = '''
<html>
<body>
<form method="POST" name="confirmation_form">
<input name="confirm" type="hidden" value="1" />
<input type="submit" value="confirm" />
</form>
</body>
</html>'''
return response
# Create an in-memory storage to store your client apps.
client_store = oauth2.store.LocalClientStore()
# Add a client
client_store.add_client(client_id="abc", client_secret="xyz",
redirect_uris=["http://localhost/callback"])
# Create an in-memory storage to store issued tokens.
# LocalTokenStore can store access and auth tokens
token_store = oauth2.store.LocalTokenStore()
# Create the controller.
auth_controller = oauth2.AuthorizationController(
access_token_store=token_store,
auth_code_store=token_store,
client_store=client_store,
site_adapter=ExampleSiteAdapter(),
token_generator=oauth2.tokengenerator.Uuid4()
)
# Add Grants you want to support
auth_controller.add_grant(oauth2.grant.AuthorizationCodeGrant())
auth_controller.add_grant(oauth2.grant.ImplicitGrant())
# Add refresh token capability and set expiration time of access tokens
# to 30 days
auth_controller.add_grant(oauth2.grant.RefreshToken(expires_in=2592000))
# Wrap the controller with the Wsgi adapter
app = oauth2.web.Wsgi(server=auth_controller)
if __name__ == "__main__":
httpd = make_server('', 8080, app)
httpd.serve_forever()
Contents: