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

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

Related

firebase auth sdk login user with email and passworrd

I'm using firebase auth sdk for an application and I'd like to log the user in. I cannot understand how it works.
To create a new user I run this code:
from firebase_admin import auth
....
def create_user(email, password):
user = auth.create_user(email=email, password=password)
return user
Now I'd like to log the user in. The auth doesn't have a method to log in the user. It has a auth.get_user_by_email(email) or some other methods to get user(s), but it has no method to check user's password. My application (API) gets email and password and I need to return the user if the email and password match.
How do I do this using the firebase sdk?
Thank you.
Logging into Firebase happens on the client, not on the server. So the Firebase Admin SDKs don't have a method to sign the user in, but all client-side SDKs (such as the Web/JavaScript SDK) have methods to sign in the user.
If you want to sign in a specific user from your Python code, you can call the REST API, or use a library like Pyrebase that wraps this REST API: https://github.com/thisbejim/Pyrebase#authentication.

Django: limit API view output to contain only data of OAuth authenticated user?

My app requires user consent to use activity data from his Strava account (Strava is a social service for athletes).
Strava uses OAuth flow for this, so the user logs in to Strava, gives his consent, and Strava redirects to a predefined URL with code added to query string that can be then exchanged for access token via another request:
def strava_redirects_to_this_view(request):
#strava redirects to this view after authentication, with code in query string
#get tokens
code = request.GET.get('code', '') # extract code from redirect URL query string
access_token = exchange_code_for_token(code) # custom function to make exchange request
I want my other app - running on another server - to get data of only authenticated user via API.
However, I don't know how to limit the output of the API to contain only the data of the currently authenticated user.
Currently my API view queries all data (activities), regardless of user:
class ListActivitiesView(generics.ListAPIView):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
I know I could limit the queryset to only logged in user if I had user registration in my app, but I would prefer not to have another registration as the user already has to log in to Strava.
How would I limit the queryset to include only currently OAuth authenticated user? Would use of python-social-auth with Strava backend be of any help here?

django social auth , create user model with email as primary key

I am trying to integrate django social auth for my website which will have Facebook and Google login. I am trying to customize the user model to make email as primary key.
Any advice ?
I tried creating a UserModel also but ended up with errors.
i tried creating a pipeline enter code here
from social_auth.backends.pipeline.user import create_user
def custom_create_user(request, *args, **kwargs):
print kwargs
return create_user(request, args, kwargs)
My aim is to have a site with Facebook And Google - oauth2 login with email as primary key !
Well I am doing facebook login for my ios app. What I am doing is
Login to facebook from my app and get the facebook access token
Send the facebook email and access token to the django backend
Then what I do is, instead of using the django default authenticate method which takes the username and password to authenticate a user, I overwrite my own authenticate method. Doing this is really easy just read Django Custom Authentication
In my custom authentication class I verify the email-token pair sent from the front using fb sdk for python and that is it. After than I can login the user using the django in built login

GAE: SimpleAuth not able set set_session() using FB ID in PROD

I am using SimpleAuth by Alex (https://github.com/crhym3/simpleauth/) in my GAE application.
When I was using it in localhost, I am login successfully using fb and google id.
After I deployed to PROD, I can still login successfully for google ids but cant login using FB ID.
def _on_signin(self, data, auth_info, provider):
"""Callback whenever a new or existing user is logging in.data is a user info dictionary.auth_info contains access token or oauth token and secret.
"""
auth_id = '%s:%s' % (provider, data['id'])
logging.info('Looking for a user with id %s', auth_id)
user = self.auth.store.user_model.get_by_auth_id(auth_id)
_attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider])
logging.error(_attrs)
logging.error(user)
if user:
logging.info('Found existing user to log in')
user.populate(**_attrs)
user.put()
logging.error(user.put())
self.auth.set_session(self.auth.store.user_to_dict(user))
For FB login, I can get the values of the users and store it datastore.
When I try to self.auth.set_session() which sets _auth cookie somehow for FB login it fails to create _auth cookie.
self.auth.set_session(self.auth.store.user_to_dict(user))
My authentication type is (Experimental)Federated Login.
I could not able to figure out why self.auth.set_session() doesn't able to create cookie for FB logins.

How to get the the User ID from an email in GAE

I'm working on a small app that will allow the user to login to the App, allow the app OAuth access to a service, then interact with the service using the app via email.
I've successfully enabled Oauth using gdata and gdata.gauth and can store/recover the Oauth token and user_id easily when the user is logged in.
However, when receiving an email, I try to get the user_id by creating a users.User(email="senders.email#gmail.com") but end up getting a None value for the user_id.
ie:
when logged in:
current_user = users.get_current_user()
current_user.user_id() #this is a valid id when the user is logged in
when receiving an email (using the mail handler):
current_user = users.User(email="sender.email#gmail.com")
current_user.user_id() #this returns None
Any hints on how to make this work?
Reading http://code.google.com/appengine/docs/python/users/userclass.html#User
Under the method call user_id, it is noted that if you create the User object yourself, the user_id field will return None.

Categories