jwt on node - how does the client pass the token b

2020-06-28 03:39发布

okay.

I think I have failed to understand an elemental part of token based authentication.

I am using node with express and am using jwt to prevent access to my site if you haven't logged in. I can create a token on the login page, and I can send it back to the client and store it in localStorage/cookie. Now if the user wants to navigate to another page they will type in a url and trigger a get request.

How do I access that token from localStorage/cookie and pass it to the server before I load the page as part of the get request. My assumption is that there should be a way of passing the token to the server - intercepting it in the middleware - and loading the page if the token is legit, or redirecting to the login page if the token isn't validated correctly.

On a post request this would be much simpler as you can fetch the token and pass it as part of an ajax call, after the page has loaded.

I have seen references to including the token as part of the request header (authorization bearer). I assume this only works for post, because if you were able to set the header parameter 'globally' then why would you bother storing on the client side in a cookie/localStorage.

So as you can see I am a little confused by the workflow. It seems like I am going against the grain somehow. Any clarity would be much appreciated.

1条回答
趁早两清
2楼-- · 2020-06-28 04:10

If you are using localStoage in order to store the JWT, then the easiest way to pass it to the server is by retrieving first the token from the localStorage with localStorage.getItem('token') (or whatever your token name is) and then inserting it in the header of the request (either it is GET or POST/PUT/DELETE). Depeding on the library you are using to handle your http requests on the client, there are different ways of doing so. In jQuery for example, you can do the following inside the AJAX request:

$.ajax({
    url: API_URL + "/endpoint",
    method: "GET",
    beforeSend: function(request){
        request.setRequestHeader("Authorization", "BEARER " + localStorage.getItem('token'));
    }
})

After this, on the server side simply access the parameters by accessing request.header options just as you would normally do. Hope this helps!

查看更多
登录 后发表回答