简体   繁体   English

缺少 Django、React 和 Rest Framework JWT 身份验证标头

[英]Django, React and Rest Framework JWT authentication header missing

I'm currently making a Login System in a Django/React with SimpleJWT.我目前正在使用 SimpleJWT 在 Django/React 中制作登录系统。

The Login Backend is in React, which posts the login credentials and gets the JWT-Token from the api.登录后端在 React 中,它发布登录凭据并从 api 获取 JWT-Token。 Then it saves the tokens to localstorage and sets it as request-header for axios, for future api calls:然后它将令牌保存到 localstorage 并将其设置为 axios 的请求标头,以供将来的 api 调用:

    const handleSubmit = (e) => {
    e.preventDefault();

    axiosInstance
        .post(`token/`, {
            email: formData.email,
            password: formData.password,
        })
        .then((res) => {
            localStorage.setItem('access_token', res.data.access);
            localStorage.setItem('refresh_token', res.data.refresh);
            axiosInstance.defaults.headers['Authorization'] =   'JWT ' + localStorage.getItem('access_token');
            history.push("");
            location.reload();
        }).catch(err => console.log(err));
};

api urls.py: api urls.py:

path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

Every API call i make with axios works and only returns after logging in... as it should be... BUT the problem is in the second Frontend, which is in Django.我使用 axios 进行的每个 API 调用都可以工作,并且只有在登录后才返回……应该是……但问题出在 Django 中的第二个前端。 It is a partly static frontend that consists mainly out of simple html-templates for the Homepage, but with a Navbar which requires User information.它是一个部分静态的前端,主要由主页的简单 html 模板组成,但带有需要用户信息的导航栏。

@api_view(['GET'])
def home(request):
    print(request.header)
    context = {
        'posts': posts
    }
    return render(request, 'MainApp/home.html', context)

I noticed that the Authentication Header are simply missing:我注意到身份验证标头只是丢失了:

  • When i try to print the user-data after logging in : request.user , output is AnonymousUser当我尝试在登录后打印用户数据时: request.user ,输出是AnonymousUser

  • After making the template view protected by setting the default permission to isAuthenticated in the settings.py like this: 'DEFAULT_PERMISSION_CLASSES' : ['rest_framework.permissions.IsAuthenticated'] Then i get 401 Unauthorized / "Authentication credentials were not provided."通过在 settings.py 中将默认权限设置为isAuthenticated来保护模板视图,如下所示: 'DEFAULT_PERMISSION_CLASSES' : ['rest_framework.permissions.IsAuthenticated']然后我得到401 Unauthorized / "Authentication credentials were not provided."

Also I checked request.META and the authorization-header (HTTP_AUTHORIZATION) is missing.我还检查了request.META并且缺少授权标头(HTTP_AUTHORIZATION)。

Is there a way to get the Token from the localstorage and add it to the request header?有没有办法从localstorage获取Token并将其添加到请求头中? I know that this is done on the client side, but why isn't it in this case?我知道这是在客户端完成的,但为什么不是在这种情况下?

It seems you are attempting to use both Django's backend and frontend capabilities together with React.您似乎正在尝试将 Django 的后端和前端功能与 React 一起使用。 What you need is to only use Django as your backend and React as your frontend.您只需要使用 Django 作为后端,使用 React 作为前端。 The concept is that, once you decide to work with Django and React, you will not need to create your frontend views with Django since this will be handled by React.这个概念是,一旦你决定使用 Django 和 React,你就不需要用 Django 创建你的前端视图,因为这将由 React 处理。

So create your models in Django and then integrate Django Rest Framework in your backend project.因此,在 Django 中创建您的模型,然后将Django Rest Framework集成到您的后端项目中。 With Django Rest Framework, you will be able to create serializers to convert your Django models to JSON so that your React frontend can work with the received data.使用 Django Rest Framework,您将能够创建序列化程序将您的 Django 模型转换为 JSON,以便您的 React 前端可以处理接收到的数据。 In a nutshell your React frontend will simply be making requests to your Django backend via an API created using Django Rest Framework.简而言之,您的 React 前端将简单地通过使用 Django Rest Framework 创建的 API 向您的 Django 后端发出请求。 There won't be any need for Django's native views and templates since React will be handling this.不需要 Django 的原生视图和模板,因为 React 会处理这些。

Your token will be added to every request you make to the backend.您的令牌将添加到您向后端发出的每个请求中。 That can be configured easily with Axios.可以使用 Axios 轻松配置。

So once you have your Django models setup.因此,一旦您设置了 Django 模型。 Immediately move to serialization of the data using Django Rest Framework.立即使用 Django Rest Framework 进行数据序列化。 You basically ignore creating Django views as those views will be handled by your React frontend.您基本上忽略了创建 Django 视图,因为这些视图将由您的 React 前端处理。 You React App will communicate with the Django backend over the interface that you created.您的 React App 将通过您创建的接口与 Django 后端通信。

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

相关问题 Django Rest 框架 + React JWT 身份验证,403 禁止在受保护的视图上 - Django Rest Framework + React JWT authentication, 403 Forbidden on protected views 使用 React 和 Django REST 框架进行身份验证 - Authentication with React and Django REST Framework React身份验证Django Rest框架 - React authentication Django rest framework 如何在 Django Rest Framework 和 React 中使用简单的 JWT 创建临时链接 - How to create temporary links with simple JWT in Django Rest Framework and React Django Rest Framework + React - 令牌与会话身份验证 - Django Rest Framework + React - token vs session authentication Django REST 身份验证不适用于 React - Django REST authentication not working with React Django REST 使用 React/ Redux 进行身份验证 - Django REST authentication with React/ Redux csrf 令牌缺少 axios 到 django rest 框架 - csrf token missing axios to django rest framework Django Rest Framework 和 React Js(Axios API 请求):在不正确的身份验证尝试后,api 返回 400 - Django Rest Framework & React Js ( Axios API Request ): After Incorrect authentication attempt, api returns 400 如何使用 react 和 axios 将 GET 请求 header 中的数据发送到 Django rest 框架? - how to send data in GET request header using react and axios to Django rest framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM