标签: django-rest-auth

drf django rest auth如何过期或删除令牌?

我正在尝试使用django-rest-frameworkdjango-rest-auth通过tivix 实现身份验证(链接到文档).我使用django shell创建了一个用户:

from django.contrib.auth.models import User
user = User.objects.create_user(username='foo', email='foo@bar.com', password='bar')
user.save()
Run Code Online (Sandbox Code Playgroud)

然后根据文档我使用django-rest-authlike(终端命令)登录用户:

curl -X POST -d "username=foo&password=bar&email=foo@bar.com" http://127.0.0.1:8000/rest-auth/login/
Run Code Online (Sandbox Code Playgroud)

它返回了一个令牌,我知道用户已经过身份验证.

现在我使用django-rest-auth文档中描述的方法注销,我仍然可以看到数据库中存在的令牌.然后我再次登录,它返回了与密钥相同的令牌.

因此,每次用户注销时,都会以任何方式删除令牌或更好的令牌.此外,文档中没有提及令牌本身是否会在经过一定时间后过期(自动删除).

如果不可能这样做,我怎样才能删除这两种情况下的令牌?

编辑:登录和退出代码

urls.py(主要):

url(r'^rest-auth/', include('rest_auth.urls')),
Run Code Online (Sandbox Code Playgroud)

settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    ...
]
Run Code Online (Sandbox Code Playgroud)

登录CURL命令:( GIVEN ABOVE).登录命令响应:

{u'key': u'e41f0a1c2f5e55569df1c41d1d5d4efb77beddee'}
Run Code Online (Sandbox Code Playgroud)

注销CURL命令:

curl -X POST -d "key=e41f0a1c2f5e55569df1c41d1d5d4efb77beddee" http://127.0.0.1:8000/rest-auth/logout/
Run Code Online (Sandbox Code Playgroud)

退出响​​应:

{u'success': u'Successfully logged out.'}
Run Code Online (Sandbox Code Playgroud)

authentication django django-rest-framework django-rest-auth

3
推荐指数
1
解决办法
5514
查看次数

电子邮件确认不存储 Django allauth

我正在使用 Django allauth 和 django-rest-auth。我通过电子邮件确认实现了身份验证。但现在我意识到它不能完全正常工作,因为我没有在数据库中存储发送电子邮件确认(在管理中看不到它们)。电子邮件确认正在按应有的方式发送,并且工作完美,只是我在数据库中看不到它们。我缺少什么?

django email-confirmation django-allauth django-rest-auth

3
推荐指数
1
解决办法
720
查看次数

Django Angular Cors错误:不允许访问控制允许起源

我已经使用django-rest-auth在django应用中实现了auth。我在settings.py中的设置:

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'corsheaders',
    'rest_framework_docs',
    'tasks'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'urls'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['*']

SITE_ID = 1
Run Code Online (Sandbox Code Playgroud)

我是从前端登录的-我已收到令牌并将其存储在本地存储中。现在,我发出一个简单的GET请求,如下所示:

  getTasks(): Observable<Task[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers, withCredentials: true  });

    return this.http.get(this.taskUrl, options)
    .map(this.extractData) …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-rest-auth angular

3
推荐指数
1
解决办法
2382
查看次数

django-rest-auth - Facebook 社交登录引发现有电子邮件的唯一约束违规

我使用 django-allauth 和 django-rest-auth 实现了注册和登录。我可以使用allauth 和rest-auth(网络和移动设备)成功使用Facebook 登录服务器。

当我尝试使用 FB 帐户登录时,其电子邮件已存在(有人已使用该电子邮件注册),它会显示注册表单。但是,当我尝试使用 Rest-auth 执行相同操作时,出现错误:

Internal Server Error: /rest-auth/facebook/

IntegrityError at /rest-auth/facebook/
duplicate key value violates unique constraint "auth_user_username_key"
DETAIL:  Key (username)=() already exists.
Run Code Online (Sandbox Code Playgroud)

我的配置:

ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_VERIFICATION = False
SOCIALACCOUNT_EMAIL_REQUIRED = True
SOCIALACCOUNT_QUERY_EMAIL = True
Run Code Online (Sandbox Code Playgroud)

django facebook-login django-rest-framework django-allauth django-rest-auth

3
推荐指数
1
解决办法
1321
查看次数

DRF request.data没有属性_mutable

我正在使用 Django 2.x 和 Django REST 框架。

我用来django-oauth-toolkit启用OAuth2身份验证、django-rest-auth登录和django-allauth用户注册。

我想在用户成功注册时在响应中生成访问令牌。为此,我使用自定义注册视图。

为此,我创建了一个函数 utils,例如

def generate_token(request, user):
    # Get OAuth application to use
    application_: Application = Application.objects.filter(
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_PASSWORD
    ).first()

    if not application_:
        raise Exception('No OAuth2 Application is setup')

    auth_data = {
        'username': user.username,
        'password': password,
        'grant_type': 'password',
        'client_id': application_.client_id,
        'client_secret': application_.client_secret
    }

    if request.data:

        mutable = request.data._mutable
        request.data._mutable = True
        request.data.update(auth_data)
        request.data._mutable = mutable

    if request.POST:
        mutable = request.POST._mutable
        request.POST._mutable = True
        request.POST.update(auth_data)
        request.POST._mutable …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework django-rest-auth django-oauth

3
推荐指数
1
解决办法
2508
查看次数

django-rest-auth + django-allauth + angular2

我正在尝试在我的 Web 应用程序中设置社交注册(google、facebook、twitter)。我使用 Django Rest Framework 作为后端,使用 Angular2 作为前端。标准注册适用于 django-rest-auth。我想用 django-allauth 设置社交认证部分。社会认证场景是:

  • 用户点击“使用 Facebook 登录”按钮
  • 他重定向到 Facebook 的授权页面
  • 他接受 Facebook 授权请求
  • 他在登录时被重定向回我的网络应用程序

但首先,我不知道如何将用户重定向到 facebook 授权页面。当我访问http://localhost:8000/rest-auth/facebook/ 时,表单所需的数据是“访问令牌”和“代码”。但是要设置这些数据,我必须从 facebook 授权页面获取它们。我对吗?我该怎么做?如何将用户重定向到社交(facebook、google、twitter)授权页面?

django-rest-framework django-allauth django-rest-auth angular

2
推荐指数
1
解决办法
1611
查看次数

Rest-auth 中的自定义用户模型:RelatedObjectDoesNotExist

我正在尝试使用 django Rest-auth库来实现注册。我遵循了安装和使用指南中的每一条说明,包括带有自定义用户序列化程序的部分。问题就从这里开始了。我们注册一个新用户,确认电子邮件,当我尝试更新用户时,我收到相同的错误:

“RelatedObjectDoesNotExist at /rest-auth/user/ 用户没有用户配置文件。”

我不知道如何进行注册以同时为他创建用户和个人资料。我知道这个问题以前已经被问过,但我没有找到任何可以解释为什么会发生这种情况的内容。我正在寻找使用 django-rest-auth 和自定义用户模型进行注册的简单工作示例

模型.py:

class UserProfile(models.Model): 
     user = models.OneToOneField(User, primary_key=True, related_name='profile')
     tagline = models.CharField(max_length=140, null=True)
     created_at = models.DateTimeField(auto_now_add=True)
     updated_at = models.DateTimeField(auto_now=True)

     @receiver(post_save, sender=User)
     def create_profile_for_user(sender, instance=None, created=False, **kwargs):
        if created:
            UserProfile.objects.get_or_create(user=instance)

     @receiver(pre_delete, sender=User)
     def delete_profile_for_user(sender, instance=None, **kwargs):
        if instance:
           user_profile = UserProfile.objects.get(user=instance)
           user_profile.delete()
Run Code Online (Sandbox Code Playgroud)

序列化器.py

class UserSerializer(UserDetailsSerializer):
    curriculumVitaeLink = serializers.CharField(source="userprofile.curriculumVitaeLink", required=False)
    class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + (
            'curriculumVitaeLink'
        )

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('userprofile', {})
        curriculumVitaeLink = profile_data.get('curriculumVitaeLink') …
Run Code Online (Sandbox Code Playgroud)

django python-3.x django-rest-framework django-rest-auth

2
推荐指数
1
解决办法
1650
查看次数

如何测试电子邮件确认?

我正在尝试使用 django-rest-auth 测试电子邮件确认视图。这是我所拥有的:

def test_verify_email(self):
    # Verify email address
    username = 'userTest'
    payload = {
        'email': 'test@example.com',
        'password1': 'TestpassUltra1',
        'password2': 'TestpassUltra1',
        'username': username,
    }
    res = self.client.post(REGISTER_USER_URL, payload)

    self.assertEqual(res.status_code, status.HTTP_201_CREATED)
    user = get_user_model().objects.get(email='test@example.com')
    # TODO retrieve the confirmation key from the user
    resp = self.client.post(VERIFY_USER_URL, {'key': ''})
    self.assertEqual(resp.status_code, status.HTTP_200_OK)
Run Code Online (Sandbox Code Playgroud)

self.client.post(REGISTER_USER_URL, payload)将发送一封包含确认代码的电子邮件,虽然我知道我可以django.core.mail.outbox在代码中检索该代码,但我宁愿不这样做,因为我必须解析电子邮件内容以查找确认代码(如果电子邮件更改)。我找不到存储在数据库中任何位置的代码,它似乎确实只存在于发送的电子邮件正文中。

我的问题是:在我的测试中是否可以在不解析电子邮件的情况下恢复此验证码?我只是想找回它来启动我self.client.post(VERIFY_USER_URL, {'key': ''})的。

以下是电子邮件内容的示例:

Hello from example.com!

You're receiving this e-mail from NomadSpeed because user detro1 has given yours as an e-mail address to …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-allauth django-rest-auth

2
推荐指数
1
解决办法
1430
查看次数

重置用户 django Rest Auth 的密码

美好的一天,我正在尝试覆盖 Django allauth 的 password_reset_email 。问题是它成功覆盖,但数据(密码重置链接、站点名称和域名)未传递到电子邮件,这最终意味着用户无法重置密码,因为没有发送链接。

我的密码重置序列化器

class PasswordResetSerializer(PasswordResetSerializer):

    def get_email_options(self):
        return {
            'subject_template_name': 'account/email/password_reset_key_subject.txt',
            # 'email_template_name': 'account/email/password_reset_key.txt',
            'html_email_template_name': 'account/password_reset_key.html',
        }
Run Code Online (Sandbox Code Playgroud)

在我的templates/registration/password_reset_email.html

{% load i18n %}
{% autoescape off %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Confirm Your E-mail</title>
    <style>
        .body {
            background-color: #f6f6f6;
            padding: 30px;
            display: flex;
            flex-direction: row;
            justify-content: center; 
            align-items: center;
        }

        .content {
            background-color: #FFFFFF;
            color: #4d4d4d;
            max-width: 400px;
            padding: 20px;
            margin: auto;
        }

        .title {
            font-size: …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-allauth django-rest-auth

2
推荐指数
1
解决办法
1393
查看次数

Django Rest Framework 自定义序列化器的 ValidationError 不起作用

我正在尝试在 Django 中设置自定义登录序列化程序并想要自定义响应,但默认响应始终显示:

{
    "username":[
        "This field is required."
    ],
    "password":[
        "This field is required."
    ]
}
Run Code Online (Sandbox Code Playgroud)

我尝试像这样设置我的序列化器:

 class MyLoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True, allow_blank=True)
    email = serializers.EmailField(required=False, allow_blank=True)
    password = serializers.CharField(style={'input_type': 'password'})
    def authenticate(self, **kwargs):
        return authenticate(self.context['request'], **kwargs)
    def _validate_email(self, email, password):
        user = None
        if email and password:
            user = self.authenticate(email=email, password=password)
        else:
            msg = _('Must include "email" and "password".')
            raise serializers.ValidationError(msg)
        return user
    def _validate_username(self, username, password):
        print("in username")
        user = None
        if username and password:
            print("in username …
Run Code Online (Sandbox Code Playgroud)

django django-rest-framework django-rest-auth django-rest-viewsets

2
推荐指数
1
解决办法
1万
查看次数