Can't JSON Web Tokens be easily stolen? - cookies

I'm reading about JWTs and I'm really confused by something which doesn't seem to be addressed:
What is stopping a malicious website from just including
localStorage.get ('secretjwt')
in their code and stealing your tokens?
If you don't store it as a cookie then anyone can access it! And if it stored as a cookie, then why not just use cookies full-on?

Cookies and localStorage are protected by same-origin policy
In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.
For example http://www.malicious.com or http://www.example.com can not access to storage in https://www.example.com
Additionaly the site should use SSL/TLS to encrypt the content and prevent the token from being stolen

Related

why browser isnt storing a cookie created in a subdomain, in the referer subdomain?

i'm facing a few problems when i authenticate usign cookies to store the token, those cookies should be delivered between subdomains, for example, i have my auth code deployed in a subdomain named services.mydomain.co and my frontend in subdomain named apps.mydomain.co,
when someone authenticates, then my auth code creates a cookie with the tag Domain like this: Domain=.mydomain.co in order to enable it to be delivered between all subdomains of mydomain.co, but the cruel reallity is that it is not working, even the browser isn't storing the cookie.
the cookie it's successful delivered in response header after authenticate but the browser isn't storing it.
im creating the cookie this way:Set-Cookie: myKey=myKeyValue;path=/;httpOnly;Max-Age=1555520000;Domain=.mydomain.co;sameSite=none
hope someone could geve me an advice and sorry for bad english.
From your example, you are setting SameSite=None without Secure. This is invalid and browsers (Chrome, Edge, Firefox, etc.) will begin rejecting this.
However, you should check DevTools in Chrome on your site to see the specific error. You can check both the Console and individual requests in the Network tab to see issues with a given cookie.
You can find more detail on https://www.chromium.org/updates/same-site/test-debug

Remember me with OAuth2 in SPA

I know the concept of OAuth2 and OpenID. in our application authentication is happening through OKTA and we receive access-token in a response.
Our architecture is a microservice-architecture and we are using EmberJS at frontend.
we have to implement remember-me functionality it will keep the user logged in for the next 30 days.
I did some study on it and came to points that will satisfy my requirements.
keep user session active for 30 days in OKTA.
refresh access token periodically based on its expiry time.
How this refreshing will work if browser is closed?
Let's say a user is logged in and closed the browser then reopened it after 3 days.
With respective to OAuth 2.0 best practices, it is recommended to have short lived access tokens. There is a dedicated RFC definition such best practices which is identified by RFC6819 - OAuth 2.0 Threat Model and Security Considerations. There are several sections which emphasise on using short lived access tokens .For example here you can see why it is recommended.
With this perspective, you may handle this situation using browser cookies. Cookies are the mechanism which helps browser and server to maintain states. In a typical web application, login state can be maintained through cookies. There are two variants of cookies.
Session cookie
Persisted cookie
The second cookie type, persisted cookies do not go out of browser when browser is closed. Of course user can clear cookies to remove them. In your scenario, you can set such a cookie to user with desired lifetime. In the backend, you need to map cookie value to a state, which should start when backend receive a valid access token/ ID Token (after authentication and authorization step).
About cookies security, there are many things you must concentrate on. But the most important are setting cookie to be secure and HttpOnly.
Also, you may store a reference to refresh token in backend correlating to the cookie. Then for each fresh usage you can use refresh token to obtain access token if you require for example API access with access token.

Security of storing Bearer token in cookies

My SPA uses React as front end and laravel API as backend.
When the user logs in (via axios and api), the api returns an access (Bearer token) as response. I use the react-cookie framework to store the access token as cookie in the Browser. This cookie will be read and used for any future request.
Is this the right way to do?
Isn't cookie data just something in the Browser that can be easily obtained by any attacker? Since it is just a file one the computer somewhere.
What is stopping an attacker from grabbing that cookie, impersonate as that user and start performing actions that requires authentication?
The token has a life span of lets say 1 year. It will only be refreshed every time the user logs in. I understand that if I set the life span shorter it will be more secure. However that will mean the user would have to log in constantly?
-----Update-----
Im not sure if any of the provided solution answered my question. A SPA app is front end based and the request can be from anywhere such as Postman, Mobile app, or any third party device that wish to talk to my backed server. So those device needs a way to store some access token locally to be used for any future request.
The only way I know this could happen is for my server to send some auth token to the requester and have it store it somewhere to be used for next request.
In this case, Im not sure if CSRF token or any other means would help my concern?
Just like facebook, if I clear my cache, I will have to re-login. That means facebook is storing something on my location computer so I can be automatically authenticated next time
I just want to add some disadvantages of storing tokens in cookies that you should also be aware of:
The max size of a cookie is only 4kb so that may be problematic if
you have many claims attached to the token.
Cookies can be vulnerable to cross-site request forgery (CSRF or
XSRF) attacks. Using a web app framework’s CSRF protection makes
cookies a secure option for storing a JWT. CSRF can also be partially
prevented by checking the HTTP Referer and Origin header. You can
also set the SameSite=strict cookie flag to prevent CSRF attacks.
Can be difficult to implement if the application requires
cross-domain access. Cookies have additional properties (Domain/Path)
that can be modified to allow you to specify where the cookie is
allowed to be sent.
------- Update -----
You can also use cookies to store the auth token, even it is better (at least in my opinion than using local storage, or some session middleware like Redis). And there are some different ways to control the lifetime of a cookie if we put aside the httpOnly and the secure flags:
Cookies can be destroyed after the browser is closed (session
cookies).
Implement a server-side check (typically done for you by
the web framework in use), and you could implement expiration or sliding window expiration.
Cookies can be persistent (not destroyed
after the browser is closed) with an expiration.
Your JS should not have access to the cookie. There are flags you can set on cookies that will help protect them and make sure they are only used for the correct purposes.
The HttpOnly flag is set on the cookie then JS will not be able to access it but it will still be sent with any request.
The SameSite flag will ensure that the cookie is only sent back to the site that gave it to you. Which prevents leakage.
The Secure flag will make it only send the cookie over a secured connection to prevent someone from sniffing it out of your web traffic.
Edit
You might want to lookup an authorization workflow but the gist of it is this:
User logs in with username and password
A JSON web token is issued upon login from the backend and sent to the browser
The JWT(JSON web token) can be stored in a cookie in the Web Storage(Session Storage) on the browser
Subsequent requests to the REST API will have the token embedded in the header or query string for authorization. With that form of authorization, your REST API understands who is making the request and what kind of resource to return based on the level of authorization
Please see #tpopov answer as he also made some really good points.

Privacy Policy(ies). Does the cookie "collect" browser data or "request" browser data?

I'm working on legal portion of my site, Privacy Policy in particular. I've done the research and found that nearly all the answers to my question (below), is generalized.
Question: Do cookies "collect" data from user browsers, or do cookies "request" then receive data from user browsers?
This seems to be a very important distinction. Do I put into my privacy policy that my site "collects" data from my users or do I "request" data from my users.
My understanding of the core functionality is that cookies request data of user browser or browser activity. Users control how their browser will respond (or handle cookies) in their browser settings. If users have the ultimate control of handling "responses" to cookies is it proper for website privacy policies to state that they use cookies to collect browser data? Isn't it more accurate to state something like: "We use cookies to request data from your browser. Depending on you have your settings, your response to our request my impact your experience." Or something along those lines.
For years the way I understood the phrase "cookies collect browser data" is that we (websites) force code (the cookie), onto your browser that opens a siv for all your activity to flow back to us. But this isn't the case at all. Cookies actually make a "request" (i.e., asks) for the user's permission first, and depending on how the user has set up their browser settings, the cookie request is honored or denied.
I'm trying to stay away from the term "collect" as a general matter. I think it's improperly used and leaves the wrong impression on users.
Has anyone else thought about this? Am I missing something?
Cookies are being stored to the system/computer - or you can say browser. Cookies are used for authentication, preferences, advertisements, performance and analytics, security purposes. Yes, we need to mention that in privacy policy or some organization also add separate cookie policy.
Following should be mentioned for cookies in policies for standard web applications:
The application may use and store cookies to your system/compute which can help better to know your preferences when you visit the website later. Cookies can also be used for authentication/session checks, advertising, performance, analytics and research and security purposes. //Remove whichever is not applied for your site.

How do web apps login you automatically on revisit without exposing the stored cookies or local storage to XSS?

There are a lot of web apps, Facebook, Google, Slack, Quora etc. that re-login you on each visit, however if they use a cookie or the browser's local storage for storing a token or login information, those could be hijacked by a third party script. How do the web apps achieve protection against this?
A script to be able to access a cookie of a certain origin (eg: facebook.com) would have to have been downloaded from the same origin, this is the same origin policy and is enforced by browsers.
Now, as you mention, an exception to this scenario would be when an attacker would manage to inject a script in the target website (XSS) so that it would be executed by another user while accessing that site, in this case the malicious script would have access to those cookies, to protect against this kind of scenarios it was introduced the HttpOnly flag, designed to make selected cookies inaccessible to client side scripts.