Skip to content

Instantly share code, notes, and snippets.

@mykwillis
Created August 28, 2015 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mykwillis/15f78ae70414deade4b4 to your computer and use it in GitHub Desktop.
Save mykwillis/15f78ae70414deade4b4 to your computer and use it in GitHub Desktop.
A Django authenticator that supports Stormpath API keys being used in BASIC HTTP Authentication
import logging
from django.contrib.auth import get_user_model
from stormpath.api_auth import ApiRequestAuthenticator
import base64
from stormpath.error import Error
from django_stormpath.backends import StormpathBackend
log = logging.getLogger(__name__)
def get_application():
"""Helper function. Needed for easier testing"""
from django_stormpath.models import APPLICATION
return APPLICATION
class StormpathApiBackend(StormpathBackend):
"""Allows the use of API keys for user authentication"""
def _stormpath_api_authenticate(self, username, password):
authenticator = ApiRequestAuthenticator(get_application())
try:
value = username + ':' + password
value = base64.b64encode(value.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + value
}
result = authenticator.authenticate(headers)
return result.account
except Error as e:
log.debug(e)
return None
def authenticate(self, username=None, password=None, **kwargs):
"""The authenticate method takes credentials as keyword arguments,
usually username/email and password.
Returns a user model if the Stormpath authentication was successful or
None otherwise. It expects three variable to be defined in Django
settings: \n
STORMPATH_ID = "apiKeyId" \n
STORMPATH_SECRET = "apiKeySecret" \n
STORMPATH_APPLICATION =
"https://api.stormpath.com/v1/applications/APP_UID"
"""
if username is None:
UserModel = get_user_model()
username = kwargs.get(UserModel.USERNAME_FIELD)
account = self._stormpath_api_authenticate(username, password)
if account is None:
return None
return self._create_or_get_user(account)
@mykwillis
Copy link
Author

Make sure to add to the AUTHENTICATION_BACKENDS setting in your project settings.py

AUTHENTICATION_BACKENDS = (
    'django_stormpath.backends.StormpathBackend',
    'myproject.backends.StormpathApiBackend',
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment