Django login() does not work if you access the page not directly, but through a redirect from another site

69 Views Asked by At

If you go to the callback page directly in the browser, the authorization works and will be saved, but if you get to the callback through a redirect from another site (in my case Twitch), the authorization will not be saved, how can I fix it?

class CallbackView(django.views.generic.RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        # some checks
        # ....

        user = django.contrib.auth.authenticate(
            self.request,
            token=self.request.GET.get('code'),
        )

        if user and user.is_active:
            # this code is triggered
            print(self.request.user.is_authenticated) # False
            django.contrib.auth.login(
                self.request,
                user,
                backend='twitch_auth.backends.TwitchOAuth2Backend',
            )
            print(self.request.user.is_authenticated) # True
            return django.urls.reverse('twitch_auth:profile')

        django.contrib.messages.error(self.request, 'Error')
        return django.urls.reverse('homepage:home')
class ProfileView(django.views.generic.TemplateView):
    template_name = 'twitch_auth/profile.html'

    def get(self, request, *args, **kwargs):
        print(request.user.is_authenticated) # True if open callback directly in the browser. False if it is redirect from Twitch
        return super().get(request, *args, **kwargs)

In addition, the sessionid on the profile page is empty if Twitch redirects to the callback and not empty if the callback is called directly

0

There are 0 best solutions below