skip to Main Content

I have an issue with Facebook authentication with Python Social Auth.

I have login with Facebook, Google and Twitter.

After login, I redirect the user to my dashboard at /user/dashboard with the use of login_redirect decorator. While it works fine with Google and Twitter, I am not able to redirect the user authenticated with Facebook.

@login_required
def home(request):
    user = ""
    if '_auth_user_id' in request.session:
        user = AuthUser.objects.get(id=request.session['_auth_user_id'])
    template = 'user/index.html'
    return render(request, template, context)

In Settings.py

SOCIAL_AUTH_FACEBOOK_KEY = '******'
SOCIAL_AUTH_FACEBOOK_SECRET = '*******'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'public_profile', 'user_location']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'locale': 'en_US',
    'fields': 'id, name, email, age_range, about, picture, location'
}
SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.10'

When I remove the login_required decorator, the user is redirected to the dashboard. But when the user tries to go to another page, there django says user is not authenticated. Is this an issue with the Facebook API or the application?

Thanks for any replies.

3

Answers


  1. 1) Check AUTHENTICATION_BACKENDS. Facebook authentication backend must be in this list.

    2) Cleanup cookies and check that facebook user is_active on you site.

    Login or Signup to reply.
  2. Here’s a quick and dirty fix. I didn’t look at all possible scenarios. This answer can be improved. First step is to get rid of the login required decorator from the redirect view. Then use the following code in the view

    if request.user.is_anonymous():
        # check if user logged in through facebook, csrf token will be validated by the middleware
        if '_auth_user_id' in request.session:
            auth_user_id = request.session['_auth_user_id']
            user_obj = User.objects.filter(id=auth_user_id)
            request.user = user_obj[0]
            userProfile = model_to_dict(user_obj[0])
        else:
            # redirect user to login page
            return HttpResponseRedirect('/login/') 
    
    Login or Signup to reply.
  3. You may have to update your app permission to provide the desired pieces of information(including email).
    Go to https://developers.facebook.com/tools/explorer/, select your app and the permission you want to provide. Then generate a new test access token.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search