How to send JWT to front end server after successful login for storage on localStorage? - node.js

In my current application after the users logs in with google (passport strategy), I generate a JWT token on the server and then I have no idea how to send it back whilst also redirecting the user to the front end website.
While searching I read that the front end should fetch the token but does that mean I have to cache the JWT until it is requested and set some cookie with the key to get the token in cache? I tried doing that but that felt like I was reinventing the wheel and opening my self to some security vulnerability.

Unfortunately, the accepted answer does not seem to answer the question.
It is a good answer for sending from the frontend (e.g. web application) to a backend (API or similar).
But I understand that you want to send the token from the backend to the frontend.
In this case, there are several way to transmit that token. They are widely used by OAuth2 Framework protocol.
Using a callback Uri
This is one of the most used technic. The backend sever generates a redirect response (status code 303) with the token in the query string. As an example
HTTP/1.1 303 See Other
Location: http://frontend.org/?token=xxxxxxxxxxx
You can also use a fragment property
HTTP/1.1 303 See Other
Location: http://frontend.org/#token=xxxxxxxxxxx
Code Exchange
Another method very similar is to generate a unique and one-time-use code that will be exchanged for the token using an additional request.
HTTP/1.1 303 See Other
Location: http://frontend.org/?code=xxxxxxxxxxx
On the fronted side, get the code and ask the token to the backend (using fetch)
POST /give/me/the/token HTTP/1.1
Host: backend.com
Content-Type: application/json
{
"code": "xxxxxxx"
}
Possible Threats
There are several threats you have to consider. They are described in RFC6819, but mitigations exist.
CSRF attacks: Use a state parameter should be used (section 3.6)
Open Redirector attacke: you should not allow client to decide the redirection URIs (section 4.1.5)
In addition, you should have a look at the RFC7636. This specification defines a way to protect the code against theft by using a random secrt generated on client side.

You can send the JWT token in header or as a payload, and at the frontend you just need to attach the JWT token with every request when sending it to the server. The server should have the logic to validate before passing the request to next middleware if the token is valid the request will be passed to next middleware else unauthorised will be return.
You can send the token in headers, payload, query whatever you like, but widely people attach token in header under Authentication.
I recommend you checking this link, it has step by step process to send and validate JWT token with Node and Express.
You can also check this for node and react.

Related

is it possible to only recieve cookies on a particular route, rather than all the routes?

I'm implementing an auth service, where I'm using the concept of access and refresh token. Storing refresh token as httponly cookie on the client side. I want to ask, how can i make only certain api routes to have cookie in their req. like, the refresh JWT token should only be sent over /auth/refresh route only.
Cookies have these options to control when they are sent, which you can set when creating them:
Domain: auth.mycompany.com
Path: /auth/refresh
So it is really a sesign question to structure server routes accordingly. Cookies cannot support multiple paths.
Generally OAuth cookies are sent from front channel requests (browser redirects) and not used for back channel requests (Ajax calls) where the browser is likely to drop them anyway.
I would avoid building to an Auth server yourself - it is a complex component - aim to use a free system such as Curity Community Edition or Keycloak instead.

secured API with a JWT

I am currently learning how JWT is working and I am making an API with.
I've made a middleware function so for each call to a secured route, the middleware is called and analyze the accessToken.
I pass the token in the header of HTTP request in the field authorization, but here is my question :
is anybody can look at the access token in the header of a HTTP request ? because if it's the case this is really not secure no? anybody can look the accessToken of his friend and make api request with ?
I already make a refresh function to get a new access token when it expires, but my /refreshroute is without middleware because the accessToken is expired when we call the refreshroute. So the /refreshroute is also not secure and it returns a new accessToken ....
please help me I really want to learn how it works...
It depends on the type of connection you are sending the request using:
If the request is sent using an SSL encryption (ie HTTPS), then you probably won't have to worry about anyone looking at the headers, as the strong encryption will not allow anyone else to look at the request except the recipient(server).
However, if there is no SSL encryption, then the payload sent to the server is exposed and open for prying eyes and vulnerable to MITM attacks.

Authorization and authentication in nodejs

how the authorization token that is sent back after a user is authenticated is stored in browser and can be used for authorization in the same api for other routes until the token is deleted from the user's database after he logs off?
I used the postman for same. And there in the Headers section i got the authorization token as a response header. But how does this all work in a real login page in the browser?
For storing the token in browser you can use cookie or browser web storage (localStorage/sessionStorage). see this link for browser web storage. For those routes which need authorization you should send back the token in a header or cookie. this blog post may help you more.
Hello you can check this sample OAuth2 based on oauth2-server you can find the repo here: https://github.com/gerardabsi/NodeJS-OAuth2
Some intro,
The Authorization token is JWT usually and is created with some secret key at the server, the library like https://www.npmjs.com/package/jsonwebtoken is used mostly in NodeJs. One can use different strategies using Passport JS to make it more secure and open for 3rd party integration (like Google, FB etc).
Now your question,
When the user initially logs into the system using his valid credentials, the server generate a JWT token with secret key and sends it in the response header. The client side (browser) saves this token in the cookie or local storage, and for the next request sends this token in the request header. The server has the secret key and can verify the token's validation and can proceed or decline the request.
One should ideally use a token that expires in 1 hour (depends on use case) or so and not use non-expiring or long expiry tokens for security reasons.
This is roughly how it works, please let me know if any doubt.

MERN-stack with react-router user authentication without redux

I'm currently trying to implement some authentication for my application, however, I have a quick question.
I set up some basic authentication on the backend, which sets a token and sends it to the frontend where it is saved in a cookie.
I read that the token is sent to the server any time I'm making an api-call, but I have trouble understanding how I'm supposed to do that.
I just read this question on stackoverflow and it seems as if the person that answers this question simply suggests two helper-functions which check if there is an item called token.
This seems like a bit of a security risk to me. Couldn't anyone just set an item called token which any random value in the local storage? Thus this person would gain access to protected routes?
If so, how would you make sure that the JWT is actually authenticated?
So, to break it down, my questions are:
Is what the answer above suggests a security risk?
How exactly to you send JWTs with your api-calls and how are they verified?
Is what the answer above suggests a security risk?
Your api should return a 401 error if a random token is used so you can handle this 401 error by clearing the token value in the cookie/local storage.
Edit: To prevent the user to access private routes with a self entered token value you may want to make an api request to check the token in the auth function of your private route (this is optionnal as a fake user will not be able to fetch the api anyway, btw keep in mind that the client have access to the javascript app code so he will always be able to "read" the restricted pages, unless you do SSR, that's why your sensitive data have to be server-side)
How exactly to you send JWTs with your api-calls and how are they verified?
Depends on your server side implementation i.e. jsonwebtoken or passport and passport-jwt works great.
On client side you'll send your jwt in the Authorization header of each request with a prefix like JWT or Bearer (depending on passport config).
Example using fetch :
fetch('/api', {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ...'
}
});

Is there any difference if I pass a user credentials as a payload, in the header, a parameter, or a query?

I am making an API for my app and I want to know if there is any difference security wise whether I pass a user's credentials as a payload, in the header, as a parameter, or as a query? Besides security, are there any differences at all such as performance, is one faster that the other?
This is for authenticating a user via username and password, from the client to the server in a GET request.
There is lot of difference when you send the credentials as payload or header or param or query. But it depends if you are using http or https. If its http then it is not at all recommended that you send the credentials at any cost over these mediums, as the request and the data can easily be traced. In case of https, you can do it but the most respected way of doing it would be to use Basic Authentication mechanism thats why its build or use OAUTH.
GET method is intended to be used to get some information from server, POST - to send data or request an action, so GET shouldn't be used for that.
You shouldn't pass authentication credentials as request parameters since they may easily leak at proxy servers, interim routers or insecure networks.
Passing them in a POST payload or request headers would minimize the probability of leaks, but anyway secure browser-to-server channel (https) must be used anyway.
While handling the authentication request on server make sure it has come from your own and not some other server. That can be implemented by using some server-generated key/token with limited lifetime and checking that token for validity when handling the POST request with credentials sent from browser.
If you issue some kind of authentication token or session id from server and keep it in a cookie, you should set HttpOnly flag to prevent access to them from JavaScript.
If you develop stateless single-page application, consider using JSON Web Token (JWT) to handle authentication/authorization claims, that would minimize the need to request permanent storage (database) on a backend and help with authentication procedures for multiple distributed resources.

Resources