简体   繁体   中英

Django, React and Rest Framework JWT authentication header missing

I'm currently making a Login System in a Django/React with SimpleJWT.

The Login Backend is in React, which posts the login credentials and gets the JWT-Token from the api. Then it saves the tokens to localstorage and sets it as request-header for axios, for future api calls:

    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:

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. 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.

@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

  • 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."

Also I checked request.META and the authorization-header (HTTP_AUTHORIZATION) is missing.

Is there a way to get the Token from the localstorage and add it to the request header? 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. What you need is to only use Django as your backend and React as your frontend. 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.

So create your models in Django and then integrate Django Rest Framework in your backend project. 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. In a nutshell your React frontend will simply be making requests to your Django backend via an API created using Django Rest Framework. There won't be any need for Django's native views and templates since React will be handling this.

Your token will be added to every request you make to the backend. That can be configured easily with Axios.

So once you have your Django models setup. Immediately move to serialization of the data using Django Rest Framework. You basically ignore creating Django views as those views will be handled by your React frontend. You React App will communicate with the Django backend over the interface that you created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM