URL token authentication in Django

后端 未结 1 746
故里飘歌
故里飘歌 2021-01-15 01:58

I\'m looking for a way in which I can send out a user an email with a url that will log them into their user. This doesn\'t even necessarily have to expire. I have found ton

相关标签:
1条回答
  • 2021-01-15 02:25

    I don't think there is something for authenticating users using url get-parameters. AFAIK Django REST framework's Tokens uses HTTP headers for tokens.

    You can write your own auth backend, it's quite easy. Here is an example

    myproject/setting.py

    AUTHENTICATION_BACKENDS = [
        'myproject.backends.UrlTokenBackend',
        'django.contrib.auth.backends.ModelBackend'
    ]
    

    myproject/backends.py

    class UrlTokenBackend(ModelBackend):
        def authenticate(self, token):
            try:
                user = User.objects.get(token=token)
            except User.DoesNotExist:
                return None
    
            if not user.is_active:
                return None
    
            return user
    
        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None
    

    Now when you will call authenticate and login function Django will check your user against each of your backends. You can manually login user like this (this is view function):

    from django.contrib.auth import authenticate, login
    
    def user_auth(request):
        token = request.GET.get('token')
        user = authenticate(token=token)
        login(request, user)
    
        return redirect('index')
    

    Update

    Or you can use this hack and do only this (without custom backend):

    def user_auth(request):
        token = request.GET.get('token')
        user = User.objects.get(token=token)
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
    
        return redirect('index')
    
    0 讨论(0)
提交回复
热议问题