【问题标题】:React, Django: How do I manage a session after a user changes their password?React,Django:用户更改密码后如何管理会话?
【发布时间】:2021-03-29 05:38:17
【问题描述】:

我正在ReactDjango 中开发一个管理面板,用于用户管理等操作。

Django 负责 ORM 和用户的登录。
当用户首次登录时,React 应用程序获取会话 id 和 csrf token。该应用程序从文档 cookie 中请求 csrf 令牌,这是用于以后 REST 查询的令牌。

问题/挑战:
其中一个应用程序组件允许用户更改密码。
但是,在成功更改密码后,会话 id 和 csrf token 过期,从那时起我执行的 REST 查询是未经授权。

如果我重新加载页面,之后会话就会过期。我尝试再次获取令牌,但它不起作用。

问题:

  • 更改密码后如何更新会话id
  • 我是否应该将用户发送到应用外让他们再次登录?

我不知道这是否是常见的处理方式。

下面是我用来获取令牌的函数:

getCookie(name) {
    console.log(name);

    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i += 1) {
        const cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (`${name}=`)) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    console.log(cookieValue);
    this.setState({
      token: cookieValue,
    });

//getCookie('csrftoken')

除了获取 csrf token 之外,我通常不使用 cookie,因此我将不胜感激。

更新

我发现问题可能是由于 Django:https://docs.djangoproject.com/en/3.1/topics/auth/default/#session-invalidation-on-password-change

当我使用 Django Rest Framework 更改密码时——遵循本教程:https://medium.com/django-rest/django-rest-framework-change-password-and-update-profile-1db0c144c0a3——我在序列化程序中使用了函数update_session_auth_hash,如下所示:

## serializer
    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()

        request = self.context['request']
        user = request.user
        update_session_auth_hash(request, user)
             
        return instance

我也不上班……

【问题讨论】:

  • 大多数网站在更改用户密码后都需要重新登录

标签: reactjs django session-cookies sessionid csrf-token


【解决方案1】:

我终于设法通过使用instance 而不是user 使其工作:

## serializer
    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()

        request = self.context['request']
        update_session_auth_hash(request, instance)
             
        return instance

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2012-03-19
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2013-07-06
    相关资源
    最近更新 更多