Django中的URL令牌认证 [英] URL token authentication in Django

查看:130
本文介绍了Django中的URL令牌认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,可以向用户发送带有url的电子邮件,该电子邮件会将他们登录到其用户中.这甚至不一定必须过期.我在会议上发现了大量的资料,但是这不是我想要的.我需要的是:

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 tons of material on sessions however this is not what I'm after. What I need is this:

  • 用户向网站提交内容
  • 他们在后台建立了一个帐户
  • 已发送一封包含链接"site.com/&token=foobar23124123"的电子邮件
  • 用户可以使用该链接登录(可选:下周)

我是否缺少一些可以帮助我的东西,或者我必须实施自己的解决方案?我是否可以仅包含Django REST框架的令牌中的令牌?

Is there something out there that I'm missing that would help me or would I have to implement my own solution? Could I potentially just include the token from Django REST framework's Tokens?

感谢您抽出宝贵的时间阅读我的问题.

Thank you for taking the time to read my question.

我正在使用Django 1.9和Python 2.7

I'm Using Django 1.9 and Python 2.7

推荐答案

我认为没有使用URL get-parameters对用户进行身份验证的东西. AFAIK Django REST框架的令牌使用HTTP标头作为令牌.

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.

您可以编写自己的auth后端,这非常容易.这是一个例子

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

myproject/setting.py

myproject/setting.py

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

myproject/backends.py

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

现在,当您调用authenticatelogin函数时,Django将针对每个后端检查您的用户.您可以像这样手动登录用户(这是查看功能):

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')

更新

或者您可以使用此hack ,并且只能执行这个(没有自定义后端):

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')

这篇关于Django中的URL令牌认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆