Node express verifying signed cookie - javascript

I am trying to use signed cookies in Node's express module, and have read the documentation, but am confused on how to verify them. As I understand it, I must verify the cookies on the server. However, how I do so is unclear to me. I will receive the cookie, and then what? Must I run a function to verify it? If so, what function? If not, and its automatic, how do I program what to do if the cookie is indeed modified? What code must I use to check for this? I intend to use these signed cookies for user authentication. So if I go to a page, and want to show different content depending on whether or not the user is authenticated, I'm not sure how to do this. If the page renders before I verify the cookie, I don't see how this would be possible. I therefore assume that I must verify the cookie before rendering the page, which leads me to ask this question, in order to figure out how to do so.
Essentially, I wish to do something like this:
if(CookieIsVerified)
{
.....
}
else if (!CookieIsVerified)
{
.....
}

You don't need to verify the cookie yourself. If you use the cookieParser middleware you can pass in a secret which will be used to sign the cookie. This means that nobody can change it.
Secondly, use the cookieSession middleware. This will take anything that is in req.session and serialize it into the cookie.
app.use(express.cookieParser('yoursecretkeyhere'));
app.use(express.cookieSession());
To check whether a user is authenticated, you can create your own middleware which checks that the current session has been authenticated. If it's not redirect to the login page or return a 401. This middleware should be used on all your routes except the login route.
Create a login route which takes credentials and doesn't use the above middleware. In here you can check username/password or tokens and if the user is a valid one, set an authenticated flag on the session. You can check this flag in your above middleware.

Related

Check whether the user has a valid credentials Jira rest API

I am using jira-client npm module to make API calls on my jira instance, I want to check that if the user has a valid credentials before doing anything else, depending on that I would either:
Tell the user that they don't have a valid username or token.
or Let the user use the project functionalities
is that possible? I am able to make calls and with invalid credentials I will got response with a special message, but I want to know if there is a specific call for checking username and token.
Using normal fetch we can use
https://myJiraInstance/rest/auth/1/session
but for jira-client module it seems there is no way, however we can use findproject method in this way we can make sure that the user has a valid credentials as well as have access to the project itself.
If there any other solution I would be happy to have it.

Angluar modfifying localStorage data to add Roles

I want to implement simple authentication and authorization in an Angular project. I want to store a JWT token, and the logged in Users data, including Roles in the Local Storage. A routing guard service would check if the currentUser in the localStorage has the Roles required for the given route.
My problem is that if the user modifies the localStorageData, he could do some things otherwise he couldn't do. I understand that he can't make any valid requests to the server, because the sent token wasn't modified.
What's the solution for this?
Example:
https://stackblitz.com/edit/angular-7-role-based-authorization-example
Instructions:
Login with: Username: user Paswword: user
Execute in
console:localStorage.setItem("currentUser",'{"id":2,"username":"user","firstName":"Normal","lastName":"User","role":"Admin","token":"fake-jwt-token.User"}')
Refresh page
You can't prevent the client from doing whatever it wants with respect to itself. As long as your server is protected that's all you can do.

React: check user authenticated by the front-end

How can I check if a token is true? I have an api with laravel passport and the front with react, the user puts email and password, the api checks and if you have user in the db it generates a token and stores it in the local storage, I have a private route, and for that I would need to know if the user is authenticated, the question is, how do I verify that the token is true? Previously I did a logic, but not worked, because if someone opened the console and put any value in the token, it returned true and the person was free to access the system.
I would use this function on my private route, if the user was authenticated I would release the route, so I would need to check on the front, if you have a better idea and can give me an example, thank you in advance!
I usually check the token to the back end server.
So at the front end I use a component that send the token to the backend (usually at componentDidMount) if the response is true I will render the private component and if it is false I will use redirect to the login page.
This is the link https://reacttraining.com/react-router/web/example/auth-workflow
Token couldn't be authenticated from frontend, frontend could save token in localStorage, you need to send the token on backend to authenticate it.
First of all understand the purpose of the problem. create logic that can used to validate the token. basically renew your token mean renew you session and the user has to refreshed with the latest data for the panel.
Token cannot be stored at the client side, it can be initiated and processed at client side but you must always validate, if system feels invalid make a force logout or make the session expired.
If you have a private route which navigate the user to another location make sure then add a additional to use the same token or generate a different token.create the route to check the flag and retrieve the existing token and utilize.
Clear the existing one and create the new one to update the system. Front end only should have navigation path if validated only approve. No client side authentication.

Authentication for a SPA and a node.js server

I have a very simple node.js app built on express which has been handling authentication using a session memory store. Basically a user logs in by:
app.post('/sessions', function(req, res) {
// check username/password and if valid set authenticated to true
if (authenticated){
req.session.user = req.body.username;
} ...
});
Then in each call from the browser a requiresLogin middleware function is called which checks to see if that user property on the session has been set.
I'm now transitioning the app to basically just provide a service that may or may not be consumed in the browser, so instead of using cookies/sessions, I'm considering changing the system so that one would post to /getToken (instead of /sessions) which would return a temporary random token associated with a user's account that could then be used for a period of time to access the service. Using the service would then require a valid token to be included in each call. (I assume this would be better than passing the username/password each time so that the password would not have to be stored in memory on the client's computer after the call to get token?)
Would such a system basically be just as secure as the above current system or Is there a much more standard/safe way to handle this? What's the standard way to handle something like this?
Thanks in advance for you help!
What you are looking for is called an HMAC and there is a great article here to get ideas on how to implement for your service.
As to whether session based security is more secure than public/private keypairs is widely debated and really depends on the implementation/application. In your case, since you want per request authentication on a public facing API, the HMAC is the way to go.

How do sessions work in Express.js with Node.js?

Using Express.js, sessions are dead simple. I'm curious how they actually work though.
Does it store some cookie on the client? If so, where can I find that cookie? If required, how do I decode it?
I basically want to be able to see if a user is logged in, even when the user is not actually on the site at the time (like how facebook knows you're logged in when you're on other sites). But I suppose to understand that I should first understand how sessions work.
Overview
Express.js uses a cookie to store a session id (with an encryption signature) in the user's browser and then, on subsequent requests, uses the value of that cookie to retrieve session information stored on the server. This server side storage can be a memory store (default) or any other store which implements the required methods (like connect-redis).
Details
Express.js/Connect creates a 24-character Base64 string using utils.uid(24) and stores it in req.sessionID. This string is then used as the value in a cookie.
Client Side
Signed cookies are always used for sessions, so the cookie value will have the following format.
[sid].[signature]
Where [sid] is the sessionID and [signature] is generated by signing [sid] using the secret key provided when initializing the session middleware.
The signing step is done to prevent tampering. It should be computationally infeasable to modify [sid] and then recreate [signature] without knowledge of the secret key used. The session cookie is still vulnerable to theft and reuse, if no modification of [sid] is required.
The name for this cookie is
connect.sid
Server Side
If a handler occurs after the cookieParser and session middleware it will have access to the variable req.cookies. This contains a JSON object whose keys are the cookie keys and values are the cookie values. This will contain a key named connect.sid and its value will be the signed session identifier.
Here's an example of how to set up a route that will check for the existence of the session cookie on every request and print its value to the console.
app.get("/*", function(req, res, next) {
if(typeof req.cookies['connect.sid'] !== 'undefined') {
console.log(req.cookies['connect.sid']);
}
next(); // Call the next middleware
});
You'll also need to make sure the router (app.use(app.router)) is included after cookieParser and session in your configure section.
The following is an example of the data stored internally by Express.js/Connect.
{
"lastAccess": 1343846924959,
"cookie": {
"originalMaxAge": 172800000,
"expires": "2012-08-03T18:48:45.144Z",
"httpOnly": true,
"path": "/"
},
"user": {
"name":"waylon",
"status":"pro"
}
}
The user field is custom. Everything else is part of session management.
The example is from Express 2.5.
I have never used Express.js, although according to their documentation on the subject it sounds like:
Cookies are stored on the client, with a key (which the server will use to retrieve the session data) and a hash (which the server will use to make sure the cookie data hasn't been tampered with, so if you try and change a value the cookie will be invalid)
The session data, as opposed to some frameworks (e.g. Play Framework!) is held on the server, so the cookie is more like a placeholder for the session than a holder of actual session data.
From here, it looks like this session data on the server is by default held in memory, although that could be altered to whatever storage form implements the appropriate API.
So if you want to check things without a specific req request object, like you said, you need to just access that same storage. On the bottom of the first documentation page, it details required methods the storage needs to implement, so if you're familiar with your storage API, maybe you could execute a .getAll() if something like that exists, and loop through the session data and read whatever values you want.
I'm curious how they actually work though.
Try to look at this answer and wiki stuff.
Does it store some cookie on the client?
Yes, it's usually a cookie with assigned session ID, which should be signed with a secret in order to prevent forgery.
If so, where can I find that cookie? If required, how do I decode it?
You shouldn't mess with a session cookie on the client side. If you want to work with sessions on the server side you should check out related express.js and connect docs.
In addition to already excellent answers, here are 2 diagrams I've created to explain Express sessions, their link with cookies and store :
chocolate cookie:
strawberry cookie:
Diagram's explanation:
Each cookie has a unique "flavor" (or sessionId). When the strawberry cookie is presented to the server (within the HTTP request), the server recognises this flavor and loads from the store the corresponding datas: Rosie's datas, and populates req.session with.

Categories

Resources