python-social-auth + mobile app - python

I have a django app and I create API for mobile app. When it comes to user authentication I simple gets login + pass and do standard django login stuff. When user is logged in I generate a token, save it and provide to the mobile app.
Now it comes to Facebook and I would like to implement python-social-auth library. I do know how to implement it for standard web, it's really trivial. But I have no idea, how to implement it into my mobile API and how to incorporate there my token stuff.
Just thinking...
Is there a possibility to do programatical auth so I would be able to create API method and call the social auth stuff from there? But how about the "Allow access to XY app to your profile" page on facebook side?
Any advice helps. Thank you in advance.

The documentation describes how you can simply provide the access_token to authenticate/create a user.
from django.contrib.auth import login
from social.apps.django_app.utils import psa
# Define an URL entry to point to this view, call it passing the
# access_token parameter like ?access_token=<token>. The URL entry must
# contain the backend, like this:
#
# url(r'^register-by-token/(?P<backend>[^/]+)/$',
# 'register_by_access_token')
#psa('social:complete')
def register_by_access_token(request, backend):
# This view expects an access_token GET parameter, if it's needed,
# request.backend and request.strategy will be loaded with the current
# backend and strategy.
token = request.GET.get('access_token')
user = request.backend.do_auth(request.GET.get('access_token'))
if user:
login(request, user)
return 'OK'
else:
return 'ERROR'

Related

How to implement single sign-on django auth in azure ad?

I have a django-based web application, a client requested that we integrate the login with Azure AD, following the documents I managed to integrate with the following flow.
In django the user types only the email, I identify the user and his company and redirect him to the microsoft ad login screen, after login, the redirect uri is activated and in my view I do some validations and authenticate the user on my system. The problem is that every time the customer is going to log in he needs to enter his credentials in azure, would it be possible with the microsoft user_id or the token acquired the first time the user logs in to login? Or another way to log in faster?
This my callback view, called in redirect_uri:
def callback(request):
user_id = request.session.pop('user_id', '')
user_internal = User.objects.filter(id=user_id).first()
company_azure = CompanyAzureAd.objects.filter(company=user_internal.employee.firm).first()
# Get the state saved in session
expected_state = request.session.pop('auth_state', '')
# Make the token request
url = request.build_absolute_uri(request.get_full_path())
token = get_token_from_code(url, expected_state, company_azure)
# Get the user's profile
user = get_user(token) #in this moment i have user microsoft profile, with token and id
# Save token and user
store_token(request, token)
store_user(request, user)
...
if it is possible to login I could store the token or user id in microsoft in my database, so it would only be necessary to login once
I think this is already answered here
Also try this
ADFS Authentication for Django
Even you can try the library in python
Django Microsoft Authentication Backend

Passing values from HTML to python using EVE rest framework

I am creating a website using html as a frontend and python as a backend using EVE framework. I have enabled token authentication for my usersRESTful Account Management. But when I pass the values to the EVE framework it gives me a 401.
var login = function (loginData) {
var deferred = $q.defer();
$http.post(appConfig.serviceUrl + 'user',{data:loginData})
here the loginData holds the username and password of my user from the html page this piece of code is inside a .js file.
My api.py holds the following authentication code.
class RolesAuth(TokenAuth):
def check_auth(self, token, allowed_roles, resource, method):
# use Eve's own db driver; no additional connections/resources are used
accounts = app.data.driver.db['user']
lookup = {'token': token}
if allowed_roles:
lookup['roles'] = {'$in': allowed_roles}
account = accounts.find_one(lookup)
return account
def add_token(documents):
# Don't use this in production:
# You should at least make sure that the token is unique.
for document in documents:
document["token"] = (''.join(random.choice(string.ascii_uppercase)
for x in range(10)))
My problem is as soon as the api.py is run it asks to provide proper credentials. How can i send the token directly to the auth mechanism so that it lets me access the db.
How will you suggest me to get rid of the authentication alert box.
I want the token to be automatically sent to the api.
If suppose I use basic authentication how can I send the username and password values directly and validate it? Without having the browser pop-up box asking for username and password
Thanks in advance.
Does it work with curl ? Refer to this question
Also, refer to this and this thread on the mailing list.

Unable to refresh a Google OAuth 2 token after update using 'Python Social Auth'

I am using Python Social Auth in a Django project and everything was working fine.
I have just updated Python social authentication to 0.2.1, and I am getting an error with load_strategy when trying to refresh a Google OAuth 2 token.
Until now I was using:
strategy = load_strategy(backend='google-oauth2')
user = UserSocialAuth.objects.get(uid=..., provider="google-oauth2")
refresh_token(strategy=strategy, redirect_uri='http://.....')
Now I am getting this error:
TypeError: load_strategy() got an unexpected keyword argument 'backend'
I was experiencing the same issue after update.
Here is example from the docs:
It’s a common scenario that mobile applications will use an SDK to signup a user within the app, but that signup won’t be reflected by python-social-auth unless the corresponding database entries are created. In order to do so, it’s possible to create a view / route that creates those entries by a given access_token. Take the following code for instance (the code follows Django conventions, but versions for others frameworks can be implemented easily):
from django.contrib.auth import login
from social.apps.django_app.utils import psa
# Define an URL entry to point to this view, call it passing the
# access_token parameter like ?access_token=<token>. The URL entry must
# contain the backend, like this:
#
# url(r'^register-by-token/(?P<backend>[^/]+)/$',
# 'register_by_access_token')
#psa('social:complete')
def register_by_access_token(request, backend):
# This view expects an access_token GET parameter, if it's needed,
# request.backend and request.strategy will be loaded with the current
# backend and strategy.
token = request.GET.get('access_token')
user = request.backend.do_auth(request.GET.get('access_token'))
if user:
login(request, user)
return 'OK'
else:
return 'ERROR'
Hope that helps

GAE/Python - redirect working from main class but not from called method

When I make a redirect from main.py, it works, but when I try to redirect from within a method that it calls, nothing happens. There is no error, the program simply does nothing.
main.py
from githubauth import GetAuthTokenHandler
class AuthUser(webapp2.RequestHandler):
"""
If no environment variable exists with the access token in it,
auth the user as an admin. If it does exist, auth them as a regular
user.
"""
def get(self):
if not ACCESS_TOKEN:
# No access token exists, auth user as admin
get_auth_token = GetAuthTokenHandler()
get_auth_token.get()
githubauth.py
import webapp2
class GetAuthTokenHandler(webapp2.RequestHandler):
"""Redirect users to github to get an access request token."""
def get(self):
self.redirect('http://api.github.com/authorize')
It depends on what kind of authorization you're doing with Github, there are two ways to do that, OAuth token authorization and Web Application Flow.
OAuth Token Authorization
If you're doing OAuth authorization, you don't have to create a request handler to fetch Github auth token, request handler is for serving specific url on your server, for this kind of task, you should use urlfetch().
So the whole flow should be like the following code:
import webapp2
from google.appengine.api import urlfetch
def getAuthToken():
github_auth_url = "http://api.github.com/authorizations"
result = urlfetch.fetch(github_auth_url)
return result
class AuthUser(webapp2.RequestHandler):
def get(self):
if not ACCESS_TOKEN:
# No access token exists, auth user as admin
get_auth_token = getAuthToken()
# do something with your token...
Redirect Authorization (Web Application Flow)
This is the case if you have applied a client id, and want to be authorized by users as a standalone web application, the steps of this kind authorization is more complicated than former one:
Redirect users to request GitHub access
GitHub redirects back to your site
If you don't know about this flow, take a look at Github OAuth - Web Application Flow
Let's see how could we do within Google App Engine
Redirect users to request Github access
This is the part which involved in your sample, simply redirect user to the authorize url with specified parameters
from urllib import urlencode
class AuthUser(webapp2.RequestHandler):
def get(self):
# ... do something ...
# Github configuration
github_client_id = "Your github client id..."
github_redirect_url = "Your url for github redirecting users back to your GAE"
github_scope = "Gtihub scopes...."
github_authorize_url = "http://github.com/login/oauth/authorize"
github_authorize_parameters = {
'client_id': github_client_id,
'redirect_url': github_redirect_url,
'scope': github_scop
}
if not ACCESS_TOKEN:
# if no access_token found on your site, redirect users to Github for authorization
url_to_redirect = "%s?%s" % (github_authorize_url, urlencode(github_authorize_parameters))
self.redirect(url_to_redirect)
Github redirects users back to your site
Github will redirect users back to your site based on the previous parameter redirect_url, so you will have to prepare another request handler for receiving redirection from Github.
(You can do this is the same request handler, but it will mess your code)
The redirection back from the step 1 will contains one parameter, code, you will need it to exchange for an access token.
from urllib import urlencode
class GithubRequestHandler(webapp2.RequestHandler):
def get(self):
# this handler need to be bind to redirect_url
# get authentication code
github_code = self.request.get('code')
# prepare data to exchange access token
github_token_url = "https://github.com/login/oauth/access_token"
github_token_parameters = {
'client_id': 'Your Github client id',
'client_secret': 'Your Github client secret',
'code': github_code}
# exchange access token
data = urlfetch.fetch(github_token_url, payload=urlencode(github_token_parameter), method='POST')
# data will perform in the following form:
# access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer
# extract access_token from the string
# save the access_token to user's model
P.S.
the code is kinda of simulation of your application flow, it needs some tuning to be able to run on production :)
You try to create a webapp2 request handler, but it cannot be done this way. get_auth_token is not a WSGI webapp2 handler instance.
If you do not change githubauth.py you have to change your main.py.
class AuthUser(webapp2.RequestHandler):
def get(self):
if not ACCESS_TOKEN:
self.redirect(to your GetAuthTokenHandler)
This will result in two redirects if you do not have an access token.
RequestHandler needs to be instantiated with a request and a response for things to work properly.
That said, instantiating one and calling methods on it from inside the handler-method of another is pretty weird.

Next query parameter doesn't work with django allauth for facebook login

I have implemented User account management into my application using Django all-auth. I have enabled login using username and password as well as with facebook connect.
The problem goes like this:
1) User visits a page http://example.com/page1/ and clicks login
2) He's taken to http://example.com/accounts/login?next=/page1/
3) When the user logs in using username and password, the user is redirected back to http://example.com/page1. But if the user logs in with facebook, he's taken to homepage.
How can I get desired behavior with Facebook login too?
You need to override the get_login_redirect_url method of django-allauth.
For this inherit the DefaultAccountAdapter class as
from allauth.account.adapter import DefaultAccountAdapter
class MyAccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
# get the next parameter from request object and return the url
And make changes on settings.py
ADAPTER = "APPNAME.FILENAME.MyAccountAdapter"
ACCOUNT_ADAPTER = "APPNAME.FILENAME.MyAccountAdapter"
This should work !
How are you generating the Facebook login link? Most likely you are not indicating the next parameter there. The allauth documentation gives this example:
Google
To get the proper next parameter you can access request.GET.next.

Categories