0

I'm working on a full stack project where users can create account, visit their profile, create blogs, read their blogs, delete their blogs etc. In order to perform all these tasks (except signup and login) the user has to be authenticated.

I'm done with the back end but i don't understand how do i send jsonwebtoken from the client side to the server side (i know how to send it from the server side). I know how to get tokens from the server and store them in browser's locaStorage but i don't know how to send them back to the server when i'm making request for reading blogs or deleting blogs or visiting back to my profile after reading all my blogs.

If i do this -

window.location.href = "/blogs";

then i won't be able to send authentication token or i should say i don't know how to send authentication token using this approach.

Here on stack overflow i read about this technique-

window.location.href = "/blogs?token=";

but i don't think developers uses this technique in their projects because as far as i know tokens are supposed to be sent through headers.

If i summarize my question i just want to know how do i send authentication token to the server as well as change the page for different routes for example a different page that shows all my blogs and another page that shows only my profile. If someone else who is not authenticated tries to visit profile route or blogs route, would get a 401 error.

It would be a great help if anyone could solve my confusion or suggest me a book or an article that solves my confusion.

Roni Dey
  • 65
  • 1
  • 6
  • 2
    you use header to send token – muasif80 Sep 08 '19 at 07:18
  • @muasif80 if i do so how do i change the window's location or in other words how do i change the page? – Roni Dey Sep 08 '19 at 07:25
  • If I understand it well, you wan't to use the JSON web token as a query parameter? Like what they talk about here https://stackoverflow.com/questions/32722952/is-it-safe-to-put-a-jwt-into-the-url-as-a-query-parameter-of-a-get-request – Karlan Sep 08 '19 at 07:41
  • @Karlan no i'm sorry if i didn't explain my question correctly. What i want to know is that how do i send jsonwebtoken using another approach so that i could send the token as well as change the page (that i'm currently on while i'm making this request) – Roni Dey Sep 08 '19 at 07:52
  • ok and you don't want to use express middleware? To first check if the user as a valid token? To protect the route in this way. – Karlan Sep 08 '19 at 08:05
  • Something like router.route('/user-profile').get(validation-middleware-function/code, code-to-get-userprofile) – Karlan Sep 08 '19 at 08:20

2 Answers2

0

Add authorization header to your request

headers: {
    "authorization": "Bearer your_token"
}

Its and example for adding header to ajax request.

Shahjahan
  • 542
  • 5
  • 12
  • i know how to add authentication token to the header but i don't know how do i change the page (that i'm currently on) using this approach. suppose that you are using fb on your mobile when you press the notification icon or news feed icon you see a different page gets open. I want to know how do i get that behavior. – Roni Dey Sep 08 '19 at 07:34
  • On your `response`, What I am telling you that every time you make a request first validate token and on success of that response, call your methods, That's it. Its a nested call. Switch or load your views on that response – Shahjahan Sep 08 '19 at 07:40
0

I will try to make it simple. As an example, I will use code from one of my project.

First, you do not explain how you check and validate token on server-side. So to make explication more complete, I will provide some code.

On the server-side, I use a simple function to check each request received and depending on verification and validation process, I will update the request received before sending it to resolver.

NB: current code used Express

In my example, I store the token inside the request header Authorization field.

const isAuth = async (req, res, next) => {
    const authHeader = req.get('Authorization');

    // if is no authorization field in header, we call 
    if (!authHeader) {
        req.isAuth = false;
        return next();
    }
    const token = authHeader.split(' ')[1]; // `Bearer XXXXXXXXXXXXXXXXXXXXX...`

    if (!token) {
      req.isAuth = false;
      return next();
    }
    // Here i decode the token
    const decodedToken = jwt.verify(token, 'SomeSecretWord');

    req.isAuth = true;
    return next();
}

On each request received, we check if the header contain an authorization token, if yes, we validate and verify token. If validation is successfully completed, I update isAuth field inside request and set it to true.

app.use(isAuth);

Now you will be able to access the isAuth inside resolvers and return data based on its value (example: throw error if false);

So now, for the client-side, since we expect token to be store inside the headers Authorization field, we need to set it before sending request.

Be sure to already have the token save on client-side. In my case, user need to login to receive a new token so he store the newly created token inside client-side storage. Now before sending each request, access token from storage and updare request header with it.

const headers = {
  Authorization: "Bearer XXXXXXXXXXXXXXXXXXXXXX",
};

const reqInit = {
  method: 'GET',
  headers: headers,
};

// send request using fetch
fetch('/someLocation', reqInit)
  ...

The problem I faced here, was to store the token between requests for a user session.

the easiest and secure way is to save it in the local or session cache (according to google after a small research) and access it on each request. While creating the json web token on server-side you can specify a expirery so if token was not used for a certain time, it will be invalid and user will need to reauthenticating to receive an other token and save it in his client-side storage.

After some research, I decide to rewrite my backend with graphql (apollo-server / express) for server-side and apollo-client for client-side. since apollo-client provides a library to manage local cache on client-side, it simplifies the task.

I hope I have answered your question and that can help you and sorry if I made a mistakes.

CedFon
  • 71
  • 4
  • Would you please explain how did you add the authorization from the client side while you were making the request?? because here i can see that you are getting the authorization token from the request. – Roni Dey Sep 08 '19 at 07:45
  • On sign in, I generate a new token and send it to client. Client receive response with the newly generated token and save it inside storage so he can access it during current session. – CedFon Sep 08 '19 at 08:17