简体   繁体   English

Django REST框架TokenAuthentication返回匿名用户

[英]Django REST framework TokenAuthentication returns anonymous user

How do I properly implement DRF TokenAuthentication without the request object returning an anonymous user when I try to log in?当我尝试登录时,如何在没有请求对象返回匿名用户的情况下正确实现 DRF TokenAuthentication?

according to the docs , when authenticated, the TokenAuthentication object provides the request.user which is the Django user instance and the request.auth which is the token instance.根据docs ,当经过身份验证时, TokenAuthentication对象提供request.user是 Django 用户实例和request.auth是令牌实例。 But even after authentication, request.user returns anonymouse user.但即使经过身份验证, request.user也会返回anonymouse 用户。

What could I be doing wrong?我可能做错了什么?

Client request:客户要求:

//function to get token
export default function axiosConfig() {
    // request header
    const headers = {
        "Content-Type": "application/json"
    }

    // Get token from local storage. Token is stored when user registers.
    const token = localStorage.getItem("token");

    if (token) headers["Authorisation"] = `Token ${token}`;

    return headers;

}

Redux action Redux 操作

import axiosConfig from "../../utils/axiosConfig";

const config = axiosConfig

export const login = (email, password) => (dispatch, getState) => {

    const body = { email, password };

    // Change to absoulte path when deploying to production
    axios
        .post("http://localhost:8000/api/auth/login", body, config())
        .then((res) => {
            dispatch({
                type: SIGN_IN_SUCCESFUL,
                payload: res.data,
            });
            console.log(res);
        })
        .catch((err) => {
            dispatch({
                type: SIGN_IN_FAIL,
                payload: err.response,
            });
            console.log(err.response.data, err.response.status);
        });
};

Django姜戈

url:网址:

from django.urls import path
from authentication.views import RegisterationView
from authentication.views import LoginView
from authentication.views import LogoutView

urlpatterns = [
    path("auth/register", RegisterationView.as_view()),
    path("auth/login", LoginView.as_view()),
    path("auth/logout/<int:id>", LogoutView.as_view()),
]

Serializer:序列化器:

The LoginResponseSerializer is used to provide response data to the client LoginResponseSerializer用于向客户端提供响应数据

class LoginSerializer(serializers.Serializer):
    """Login serializer"""

    username = serializers.CharField()
    password = serializers.CharField(required=True)


class LoginResponseSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            "id",
            "username",
            "first_name",
            "last_name",
            "email",
            "is_active",
            "is_staff",
        ]

        read_only_fields = ["id", "is_active", "is_staff"]

View:看法:

class LoginView(APIView):
    """Login View"""

    permision_classs = [permissions.AllowAny]

    def post(self, request):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            print(serializer.data) # Data is present

            user = authenticate(request, **serializer.data) # Valid credentials. User object is returned.
            response_serializer = LoginResponseSerializer(user)

            if user is not None and login(request, user):
                print(request.user) # User is anonymous

                token, created_token = Token.objects.get_or_create(user_id=user.id)

                if isinstance(created_token, Token):
                    token = created_token

                return Response(
                    {
                        "user": response_serializer.data,
                        "status": {
                            "message": "user authenticated",
                            "code": status.HTTP_200_OK,
                        },
                        "token": token.key,
                    }
                )

            raise serializers.ValidationError(
                "Invalid Username or Password. Please try again"
            )

        return Response(
            {"error": serializer.errors, "status": status.HTTP_403_FORBIDDEN}
        )

Since you are using Token authentication, your users will be authenticated with the token in the header, for each request.由于您使用的是令牌身份验证,因此对于每个请求,您的用户都将使用标头中的令牌进行身份验证。

Django login() is useful in case of SessionAuthentication. Django login()在 SessionAuthentication 的情况下很有用。 Where user is stored in the session object in django, identified by the session cookie.其中 user 存储在 django 中的 session 对象中,由 session cookie 标识。

In your view, you don't have to call the login method.在您看来,您不必调用 login 方法。 Just return the token and whatever extra information you want.只需返回token和您想要的任何额外信息。 And make sure you are sending this token in every request to authenticate this user.并确保您在每个请求中发送此token以验证此用户。

EDIT: And the clarification about the request.user in the documentation of DRF, is about accessing the authenticated user in the other view where you provide token in headers.编辑:关于 D​​RF 文档中request.user的澄清是关于在另一个视图中访问经过身份验证的用户,在该视图中您在标头中提供令牌。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django Rest框架TokenAuthentication不起作用 - django rest framework TokenAuthentication not working Django REST Framework TokenAuthentication 一般在 Django 中进行身份验证 - Django REST Framework TokenAuthentication to authenticate in Django generally &quot;detail&quot;: &quot;方法 \\&quot;GET\\&quot; 不允许。&quot; 在 TokenAuthentication Django 休息框架中 - "detail": "Method \"GET\" not allowed." in TokenAuthentication Django rest framework 使用 Django REST Framework 的 TokenAuthentication 查询字符串中的令牌 - Token in query string with Django REST Framework's TokenAuthentication 如何在django-rest-framework中使用TokenAuthentication for API - How to use TokenAuthentication for API in django-rest-framework 带有 JWT 用户身份验证的 Django Rest 框架(获取匿名用户) - Django Rest Framework With JWT user authentication (getting anonymous user ) 检查用户是否使用 django TokenAuthentication 进行身份验证 - Check if user is authenticated with django TokenAuthentication 根据请求的类型,在API视图的一部分上应用tokenauthentication Django rest框架 - Apply tokenauthentication Django rest framework on part of the API view based on the type of the request 在 django rest 框架(使用 TokenAuthentication)公共 APIView 上获取 CSRF 令牌丢失错误 - Getting CSRF token missing error on a django rest framework (with TokenAuthentication) public APIView 在 Django Rest 框架中使用 Tokenauthentication 进行身份验证时,last_login 字段未更新 - last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM