difference between res.header(x-auth, JWTtoken) and res.cookies(JWTtoken)? - javascript

I have seen across all blogs and articles is that there is two ways to handle JWTtokens, put them inside localStorage which subjected for XSS attack or put them inside Cookies and set httpOnly and secure flags to avoid XSS.
Using localStorage
For every request to the server you extract the token out of the localStorage and append it to Authorization : Bearer <Token> manually.
Using Cookies
It is handled server side since it won't be accessed by JS client side, what you do is res.cookies(token), and it is going to be sent automatically for every subsequent call unlike localStorage
But lately i saw some developers simply put the token in the headers using res.headers('x-auth', token).
Is it a third way to handle JWT?
Would the X-Auth header set for every subsequent request to the server like cookies automatically or you have to set it manually (like in case of localStorage) ?
Are tokens in X-Auth header cannot be accessed by JS and secure like cookies?
what is the difference between doing it your way res.header('X-auth') and res.cookie(token) ?
Finally what is the best way to do it if my API is consumed by by ReactJS web app and react-native mobile application?
Thanks

Related

Do I have to store tokens in cookies or localstorage or session?

I am using React SPA, Express, Express-session, Passport, and JWT.
I'm confused about some of the different client-side storage options to store tokens: Cookies, Session, and JWT / Passport.
Do tokens have to be stored in cookies, even if I can store them in req.sessionID?
Many websites use cookies to store shopping cart tokens. So far I have stored shopping cart data based on the session ID without adding any cookies.
So when users visit my website, I will match it with their
req.sessionID and then retrieve the data in the database like shopping carts and user session.
Do I need to store cookies? I can access it via req.sessionID to get the data needed.
And the second
I have made authentication using a passport-google-oauth20.After I successfully login, the data is saved into the session. and to send it to the client I have to send it via the URL query ?token='sdsaxas'.
in this case I get a lot of difference of opinion. someone saved it
into local storage and someone saved it into cookies by converting it to a token using JWT.
jwt.sign(
payload,
keys.jwt.secretOrPrivateKey,
{
expiresIn:keys.jwt.expiresIn // < i dont know what is this expired for cookies or localstorage ?
}, (err, token) => {
res.redirect(keys.origin.url + "?token=" + token);
});
Can I indeed store everything related to the session by using sessionID (without cookies or localstorage)?
Only by doing fetch once or every page refresh and retrieving the data and then saved into redux because I use React SPA.
This answer is based on the stateless approach and therefore it doesn't talk about the traditional session management
You have asked two altogether different questions:
Shopping cart - which is more related to business functionality
OAuth 2 & JWT - which is related to security and authentication
As a user of an ecommerce website, I'd expect that any item I add to my shopping cart from my mobile device while commuting to my workplace, should be available in the cart when I login to the website from my PC after reaching home. Therefore, the cart data should be saved in the back-end DB and linked to my user account.
When it comes to authentication using OAuth 2.0, the JWT access token and / or refresh token need to be stored somewhere in the client device, so that once the user authenticates himself by providing login credentials, he doesn't need to provide his credentials again to navigate through the website. In this context, the browser local storage, session storage and cookies are all valid options. However, note that here the cookie is not linked to any session on the server side. In other words, the cookie doesn't store any session id. The cookie is merely used as a storage for access token which is passed to the server with every http request and the server then validates the token using the digital signature to ensure that it is not tampered and it is not expired.
Although all three storage options for access and / or refresh tokens are popular, cookie seems to be the most secured option when used in the correct way.
To understand this better, I recommend you read this and this along with the OAuth 2.0 specification.
Update On 16-Feb-2019
I said earlier that cookie seems to be the most secured options. I'd like to further clarify the point here.
The reason I think browser localStorage and sessionStorage do not provide enough security for storing auth tokens are as follows:
If XSS occurs, the malicious script can easily read the tokens from there and send them to a remote server. There on-wards the remote server or attacker would have no problem in impersonating the victim user.
localStorage and sessionStorage are not shared across sub-domains. So, if we have two SPA running on different sub-domains, we won't get the SSO functionality because the token stored by one app won't be available to the other app within the organization. There are some solutions using iframe, but those look more like workarounds rather than a good solution. And when the response header X-Frame-Options is used to avoid clickjacking attacks with iframe, any solution with iframe is out of question.
These risks can, however, be mitigated by using a fingerprint (as mentioned in OWASP JWT Cheat Sheet) which again in turn requires a cookie.
The idea of fingerprint is, generate a cryptographically strong random string of bytes. The Base64 string of the raw string will then be stored in a HttpOnly, Secure, SameSite cookie with name prefix __Secure-. Proper values for Domain and Path attributes should be used as per business requirement. A SHA256 hash of the string will also be passed in a claim of JWT. Thus even if an XSS attack sends the JWT access token to an attacker controlled remote server, it cannot send the original string in cookie and as a result the server can reject the request based on the absence of the cookie. The cookie being HttpOnly cannot be read by XSS scripts.
Therefore, even when we use localStorage and sessionStorage, we have to use a cookie to make it secured. On top of that, we add the sub-domain restriction as mentioned above.
Now, the only concern about using a cookie to store JWT is, CSRF attack. Since we use SameSite cookie, CSRF is mitigated because cross-site requests (AJAX or just through hyperlinks) are not possible. If the site is used in any old browser or some other not so popular browsers that do not support SameSite cookie, we can still mitigate CSRF by additionally using a CSRF cookie with a cryptographically strong random value such that every AJAX request reads the cookie value and add the cookie value in a custom HTTP header (except GET and HEAD requests which are not supposed to do any state modifications). Since CSRF cannot read anything due to same origin policy and it is based on exploiting the unsafe HTTP methods like POST, PUT and DELETE, this CSRF cookie will mitigate the CSRF risk. This approach of using CSRF cookie is used by all modern SPA frameworks. The Angular approach is mentioned here.
Also, since the cookie is httpOnly and Secured, XSS script cannot read it. Thus XSS is also mitigated.
It may be also worth mentioning that XSS and script injection can be further mitigated by using appropriate content-security-policy response header.
Other CSRF mitigation approaches
State Variable (Auth0 uses it) - The client will generate and pass with every request a cryptographically strong random nonce which the server will echo back along with its response allowing the client to validate the nonce. It's explained in Auth0 doc.
Always check the referer header and accept requests only when referer is a trusted domain. If referer header is absent or a non-whitelisted domain, simply reject the request. When using SSL/TLS referrer is usually present. Landing pages (that is mostly informational and not containing login form or any secured content) may be little relaxed ​and allow requests with missing referer header.
TRACE HTTP method should be blocked in the server as this can be used to read the httpOnly cookie.
Also, set the header Strict-Transport-Security: max-age=; includeSubDomains​ to allow only secured connections to prevent any man-in-the-middle overwrite the CSRF cookies from a sub-domain.
LocalStorage/SessionStorage is vulnerable to XXS attacks. Access Token can be read by JavaScript.
Cookies, with httpOnly, secure and SameSite=strict flags, are more secure. Access Token and its payload can not be accessed by JavaScript.
BUT, if there is an XSS vulnerability, the attacker would be able to send requests as the authenticated user anyway because the malicious script does not need to read the cookie value, cookies could be sent by the browser automatically.
This statement is true but the risks are different.
With cookies, the access token is still hidden, attackers could only carry out “onsite” attacks. The malicious scripts injected into the web app could be limited, or it might not be very easy to change/inject more scripts. Users or web apps might need to be targeted first by attackers. These conditions limit the scale of the attack.
With localStorage, attackers can read the access token and carry out attacks remotely. They can even share the token with other attackers and cause more serious damage. If attackers manage to inject malicious scripts in CDNs, let’s say google fonts API, attackers would be able to siphon access token and URLs from all websites that use the comprised CDN, and easily find new targets. Websites that use localStorage are more easily to become targets.
For the sake of arguments
A pen-testing might flag your use of localStorage for sensitive data as a risk.
If it was ok for JavaScript to read access token from localStorage from an XSS attack, why do you think the httpOnly flag is still recommended by everyone.
Recommendation from OWASP
Do not store session identifiers in local storage as the data is always accessible by JavaScript. Cookies can mitigate this risk using the httpOnly flag.
https://medium.com/#coolgk/localstorage-vs-cookie-for-jwt-access-token-war-in-short-943fb23239ca
HTTP is a stateless protocol. Read that answer for more detail, but essentially that means that HTTP servers, such as your web server, do not store any information about clients beyond the lifetime of one request. This is a problem for web apps because it means you can't remember which user is logged in.
Cookies were invented as the solution to this. Cookies are textual data that the client and server send back and forth on every request. They allow you to effectively maintain application state data, by having the client and server agree on what they remember each time they communicate.
This means, fundamentally, you cannot have a session without a cookie. There must be a cookie that stores at least the session ID, so that you can find out which user is currently logged into your app by looking up the session. This is what express-session does: the documentation for the main session method explicitly notes that the session ID is stored in a cookie.
so my question is do I need to store cookies?because I can access it via req.sessionID to get the data needed.
You don't need to store cookies. express-session will do this for you. Your application as a whole does need to store a cookie; without it, you wouldn't have a req.sessionID to look up.
According to my experience, just store token in localStorage.
localStorage:
it can store information up tp 5MB. You do not need to ask user's permission to store token in localStorage.
The only concern is that whether the target device support localStorage api.
Check here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
It is widely supported. But according to my experience, if you have an ios app, and there is a html page in this app which ask the user to store token (also called webview), the localStorage api cannot be recognized and throw an error.
The solution is simply i just put token in url and transfer it every time. In webview, url is not visible.
Cookie:
It is a very old style to store info locally. Storage in cookie is relatively small and you need to ask user's permission in order to store token in cookie.
Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.
(https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)
Do not store token in sessionStorage or redux.
Data stored in sessionStorage will be lost if the tab is closed. If a user accidentally closed a tab, the token is lost and the server will not be able to identify the current user.
Token stored in redux is not different to be stored in other js files. redux store is just another js file. information stored in redux get lost for every page refresh.
In conclusion,
most of the time, token is stored in localStorage if using a modern style. In certain scenarios, you can store token in cookie and may be put in url sometimes. But never store in session.
Hope it helps.

How to share one token between multiple Vue apps

I want to find a method how to share one token between multiple vue apps. With this i can create multiple single page application mimicking the microservices on back end. I was thinking about putting it into Vuex and save the state in localstorage/cache however i cannot retrieve the same state for another app. Any suggestions?
For such case using cookies would be appropriate.
Unlike localStorage, it is possible to share same cookie across parent domain (example.com) and subdomains (sub-domain.example.com). It is done by specifying domain property of cookies as wildcard - .example.com (note the leading dot in front of the domain name). Relevant answer
Depending on application architecture, you can manually read cookie in front-end on application startup, verify if user is singed in and save it to the store.
In case API is hosted on a subdomain as well, it is possible to make a request to the API (if cookies domain is specified, cookies header will be sent with a request) and verify if user is authorized to access the app. It is only suggested, if API doesn't check token in different way (e.g. in payload or Authorization header).
In both cases, it would be suggested to create API endpoint to verify token, call it on application mount and handle appropriately.
Also, since managing cookies manually may get quite uncomfortable, using third party libraries will provide similar API as using localStorage. For example: js-cookie.

NodeJS CSRF Protection with Express, GraphQL and CORS enabled

I am creating a web service very much like shopify but using only JS. Nodejs express for an API with GraphQl and Cors enabled. VueJS for frontend. My authentication is running with JWT. But I have things like anonymous checkout so i need a CSRF protection. The thing is my API is not a router. My router is in the frontend and im only getting the data I need via Graphql through Axios calls to the API. I took a look at the csurf module and tried it out but currently the way im getting a CSRF token to the frontend is with a /getCSRFToken endpoint on the API which i've read is not a good practice and the other thing is It's enabled to access to everyone because of the CORS enabled.
This is the main source of information I have: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
I don't know how to exactly set up the CSRF protection without having am API route for getting the CSRF token and sending it as a cookie through the response and generally make the whole thing secure with the best practices.
I was also thinking about restricting access to the API only for the domains of the shops that are in the system but don't now if that will be any good either.
Any suggestions are welcome
You can generate the cookie client side (using window.crypto), then have the JS read it and send it in a header, the server simply has to verify that they match. But this is vulnerable to the fact the cookie is not HttpOnly (because your JS needs to read it!). For this reason, this method is not best practice, but it is better than nothing.
It also does not prevent users from issuing requests from curl and such once they figure out that they only need to provide a matching cookie and header, but they still cannot issue requests on behalf of other users unless they have the target users authorisation credentials.
There actually isn't anything wrong with having an API route which generates a token per request, although it does result in doubled request density (you need a new token for each request!). The reason for this is that an attacker cannot read the response from an external site (CORS will prevent this). Then you are not vulnerable to any cookie exploit, since you never store a cookie in the first place.
Edit: I see you hint at having CORS * enabled for this endpoint to be public. If your API really is public then you'll have probably better off using OAuth2/JWT authentication instead, this way CSRF becomes irrelevant, since the authentication does not come from cookies.
Trying to keep a value across multiple requests encounters difficulty with history functionality, so it's recommended to either use a token per request or...
You could also store a cookie from the getCsrfToken() request and keep it valid for some time, but make it HttpOnly, since it was issued by the API, the API will be responsible for making sure that it is receiving a valid CSRF token.
The issue with both of the above is that if you want true anonymity then you can't tie these tokens to a particular user, so one user could avoid the CSRF checks on behalf of another by using their own CSRF token!
If you can come up with some way around that whilst maintaining anonymity then the server can check the validity of the tokens that it is receiving, such that one user cannot use their token on behalf of another.
Your last idea (assuming that you want true anonymity) is probably the best. Provided that the user agent is trustworthy, the referer and Origin headers cannot be tampered with, so if you are happy to lock down your API to only the domains which your JS is running on, then doing a referer/Origin check server side will not be easily worked around by an attacker. This isn't best practice, but is practically effective.
Again, curl requests and such can be issued freely, but they can only be issued on behalf of another user if the attacker has the user's authorisation credentials.
The last thing to note is that CSRF is an alternative attack vector to XSS, but if you have XSS vulnerabilities, then CSRF defences usually become obsolete, so make sure that you defend XSS first, before implementing CSRF defence.

How can I send cookies of a Web Api back to it from a different front-end application

I have a web application that serves only static contents - HTML, CSS and JavaScript. I have another application which is an ASP.NET Web API. Both applications are on same machine on different ports (for testing purpose and they could be on different machine or domain in production environment). When I browse the web application, it gets both cookie as well as form token of Anti CSRF on first ajax call from Web API. So I am setting the body token as header with setRequestHeader function of XMLHttpRequest. It doesn't seem there is any need to set the cookie token since cookies are restricted with HttpOnly Attribute for a security reason and as far as I know browser is responsible to send the cookie to whichever domain the cookie belongs to.
However, when I make consecutive ajax calls, instead of both these tokens being passed back to server, only the header token is being received by the server.
Currently the Web API is set with CORS restriction for the web application. But if the problem was related to cross origin then I guess, headers could not have been passed as well, correct me if I am mistaken.
So can anyone help me with this problem? I just want to be able to send cookies from one application to another without compromising in terms of security.
Take a look Cookies With My CORS and Set-Cookie in HTTP header is ignored with AngularJS

What are some alternatives to CSRF tokens in Laravel?

For non-PHP based web-clients (JSON) making use of Laravel Controllers; What would be the potential alternatives to CSRF tokens in Laravel to secure web requests?
If your API uses an authentication scheme that does not depend on the authentication token being sent automatically by the browser (which practically means the token or session id is not in a cookie), your API is not vulnerable to CSRF. This includes token-based auths, unless the token is stored in a cookie.
If cookies are used to pass auth tokens (including session ids, which is the same in this respect), you need CSRF protection for all requests that change server state (mostly data, but also logon status or privilege level for example).
For Laravel, you need to pass the token value from the XSRF-TOKEN cookie as a request header value in X-CSRF-TOKEN. With jQuery, this is easily accomplished in any client framework by reading the cookie value and adding it to requests:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': csrfCookieValue
}
});
If your client is not browser based, you can implement a different protection than the one in Laravel already. OWASP has a cheat sheet on what your options are, probably double submit is the easiest to implement while being reasonably secure. In very short, you create a random token and send that to the server as a cookie and also as a request header, the server only compares whether the two (cookie and header) match. This works, because an attacker on a differnet origin (domain) cannot set or access a cookie for the application origin due to the same origin policy in browsers.
I think the whole point on using a csrf token is for use inside the app. If you are sending your request via ajax from the app itself then you can simply append the csrf_token to the request. However, if you are sending data from an external source via json then the best way would be to use oAuth to secure access to your api. Luckily laravel has already built this functionality with laravel/passport so implememting it is fairly straightforward.

Categories

Resources