Authorization between nuxtjs and the API

I have a Vuejs application built using Nuxtjs . I also use Django as an internal server, and I created an API to interact with the backend server (Django) and the interface (Vuejs / Nuxtjs). And any API-related fetching is done in the AsyncData function page to display server-side data using axios . In addition, I use json authentication authentication, and the API generates a jwt token after a successful login, which is stored in a cookie. Thus, the request authorization header for the token will always be checked for the backend. If the request comes from a registered user (an authorized token), then return authenticated json data or return failed authentication data.

Problem:

When the user navigates to the application, I would like to check if the user is authenticated. If the user is authenticated, draw an authentication page. If not, display the page without authentication.

My thoughts:

When fetching from an application in the AsyncData function , I would check if there is any value for the cookie. If after that a token with the request authorization header is sent. But, since the page will be displayed on the server first, and not on the client side (where there is actually a cookie), it will never find a token for authorization.

How can I check if the user has already been registered or not so that I can receive authenticated and not authenticated data, respectively, from the API?

Update

When I log in successfully (after authorizing the email and password), I get the json response back with the token that I set in the cookie as follows:

 this.$cookie.set('my_auth_token', this.token, {expires: 15}) 

How can I get cookies on the client side and in the nuxt server for server-side rendering?

+5
source share
2 answers

Cookies are displayed on the Nuxt server (Express) through middleware .

In particular, they can be read from the req.headers.cookie property. You can see an example of the implementation of this in the Nuxt Documentation .

As for your implementation: selecting privileged data from your API using Node seems like the perfect way to delegate session processing for this single service (and not both) and provide SSR for your users.

If you decide to do session processing in the Django service instead, you need to “forward” your cookies by passing them to the axios request axios .

+2
source

I did something similar using Firebase validation. There is an example project example on Github, as well as a blog post describing important files and configurations used in the application.

0
source

Source: https://habr.com/ru/post/1273415/


All Articles