Not able to handle Authorization using JWT - node.js

Im trying to create a protected route , once the user logs in user is issued a token and this token is checked when user tries to access a protected resource . Im able to generate the token and send it back as a response as the below code,
const token = jwt.sign({_id:found._id.toString()},process.env.KEY);
res.header('token', token );
res.render("dashboard");
So after a user is logged in , i go to the dashboard and i can see the response header where token is set as token .But when i try to navigate to the secret resource page the auth handler gets a request,but the request does not have a token in the header so im not able to verify it.
router.get('/secret',auth,function(req,res)
{
res.render('secret')
}
);
Trying to figure out how to set the token header correctly so it is issued and can verify it.

on client side, you should send token in header as authorization
after that, you can receive client's token on backend side using
req.get('Authorization')
and verify it using
jwt.verify

Related

Working with JWT , how to set it and use it for authentication?

Example Scenario :-
I am using HTML and JS in frontend .
For backend I am using Express .
For Authentication I am using JWT .
Basic thing I know is that JWT is generally set in Authorization header when it is sent back to server .
What I want :-
Let us assume client requested post /user/login route giving their credentials through form . Auth middleware will verify the credentials and generate a jwt token using some payload .
My problem starts here , how to set this jwt on the client side and get it back in the header while navigating user to an authenticated page where I want user to redirect when they successfully login .
Something like below :-
app.post('/user/login' , authMiddleware , async (req , res) => {
res.redirect('/user/createTask')
}
Assume /user/createTask is expecting jwt which it will verify before letting user to enter into the route .
So what has to be in the authMiddleware so that jwt is set in the client side in local Storage or somewhere and get it back in the Authorization header .
If there are things to be done on client side to make it work , Please suggest that too .
How this whole scenario will work ?
If you're sending the credentials through a form, then you won't be able to capture the response when you send a redirection response. The redirect will be handled by the browser, and your JS will not have access to anything that you send in the response.
For this scenario to work, you would have to call the post /user/login endpoint through javascript. Then you can receive the response from your server. Read any tokens from it (which can be e.g. in the body of the response), set the tokens somewhere in store and then call the /user/createTask endpoint. If you want to use JWTs sent in an Authorization header, you will have to call all your endpoints through javascript. The browser can't add an Authorization header to the request. You can store the token in a cookie (the response from login can set the cookie), then the browser will send the cookie together with the request.

Setting a request header in NodeJS

I'm quite new to NodeJS. Lately, I've been trying to create a Login page with authentication using JWT and I've been running into the same error for a week now.
Here is my logic though:
user sign up and is been given an access token using JWT via
const token = jwt.sign({username:this.username, _id: this._id}, config.get('private keys));
req.headers.authorization = token;
While login in, I did this;
const token = req.headers.authorization;
if(!token) return res.send("Access denied");
...
But then, every time I try to login, I always get Access denied, I don't know if it should be req.headers.authorization or res.headers["authorization"], or if the problem is in the sign up page.
Can you tell us how you are sending the http requests?
Normally, when using postman, you should get a token with your default login route and then add the token in a new header with "Authorization" name and "Token " in value.

How can i authorize my jwt token in postman

I have created my protected routes and i will like to access the protected routes using jwt token from postman
One way to get around this is this:
Store JWT in session/cookie for the user.
Send this as a request header. You can call it x-api-token or whatever you like.
Keep the public key for JWT in server's environment or file-system.
Read the value of header i.e. x-api-key
Verify using any JWT library to make sure it's authentic.

Laravel sanctum token after Authorization

I am using Laravel Sanctum in my project.
I have created the middleware to add the authorization header (Bearer token) for every API request. Auth user has token but it is hashed in the database. I want to send the token (which is authorized) for the next requests. How can I get the authenticated token value (like JWT token)?
You can get the plainTextToken only when it's first created. Once it's created, there is no way to get it again. It is returned in the token/create response body. Capture it and don't lose it, it will be the only way for that user to communicate/authenticate with your sanctum protected routes. Once it's created a hashed (non-decryptable) version is saved to the database. The plain text token that you save from the tokens/create method is hashed and compared to this to confirm the identity of the user. Unlike JWT, you won't get new iterations of the same token after creation.
See more here: https://laravel.com/docs/8.x/sanctum#issuing-api-tokens
you cab catch token from header like this
$token = null;
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
if (strpos($headers['Authorization'], 'Bearer') !== false) {
$token = str_replace('Bearer ', '', $headers['Authorization']);
}
}

How do I handle OAuth refresh token?

When I authorize on my OAuth server it returns me access / refresh tokens:
access_token: "ZjJlMGM2MDcxNDg5MDQ1NzA4ZjkyNzRiOTIwM2E5MWI4N2M0MWU0ZD..."
expires_in: 3600
refresh_token: "NWZjMzQ3YjNjMmY5YTEzYzMxMDYzNGVhNzRiNjAxZTdmZTdjNzE3z..."
scope: null
token_type: "bearer"
How do I use them in my client side javascript application?
Is it okay to save access token and refresh token in the cookies?
(is it safe? - but anyway I dont see any other place where I can
store them...)
I can request protected resources like this: /api/user?access_token=TOKEN . And when I access them I really get my protected data successful. But what will happen when this access token expired? Will it be automatically refreshed, or do I need to handle it manually?
Why do I need refresh token and when I should send it to the server?
three-legged ( User---client ---- Oauthserver)
1)In 3 legged authentication access Token is stored at the client side and is never transferred to the user.
two legged (user ----Oauthserver)
In 2 legged authentication the token is stored at the user side. Probably in the cookie.
2)When the token expires user explicitly has to use the refresh token to get a new auth token.
3) Each Auth token has an expiry and instead of reauthenticating itself with a username/password,User can present refresh Token to get a new valid Auth token.

Resources