Does JWT share/store the secret for signing on both the client and server? - json

I am working through some architecture issues in my head related to JWT authentication security and I'm trying to figure out the following:
How does JWT securely pass a secret between server and client?
Take a look at the below excerpt from from https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/ ....................
CSRF can be prevented by using synchronized token patterns. This sounds complicated, but all modern web frameworks have support for this.
For example, AngularJS has a solution to validate that the cookie is accessible by only your domain. Straight from AngularJS docs:
'When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.
You can make this CSRF protection stateless by including a xsrfToken JWT claim:'
{
"iss": "http://galaxies.com",
"exp": 1300819380,
"scopes": ["explorer", "solar-harvester", "seller"],
"sub": "tom#andromeda.com",
"xsrfToken": "d9b9714c-7ac0-42e0-8696-2dae95dbc33e"
}
How does the client create and send a valid request including the xsrfToken claim unless it can first sign the JWT after including the claim? (This xsrfToken after all is what's supposed to keep EvilBob from forging a request right?)
More details regarding my current understanding of the JWT XSRF process can be found here http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/.

I can explain how Stormpath does it, there are some other ways as well. Stormpath includes a 'kid' (key id) field in the JWT header, which is the identifier for the API Key ID / Secret pair. The JWT was signed with the Secret, and the ID is stored in key id field. When Stormpath validates the token, it can retrieve the secret. This works across servers and services but is never passed to the client. Using the client to glue separate services together with the secret is extremely insecure.
The client SHOULD NOT generate the JWT, this needs to be done on the server. The server knows the XSRF token and can sign it in the JWT and put it in the cookie.
Hope this information helps!

The article appears to call this the "synchronized token pattern", however the solution described better fits with the Double Submit Cookies method rather than the Synchronizer Token Pattern.
Double submit cookies involves sending the cookie value in a header or body as well as sending it with the browser cookies that are automatically sent. If you are not supporting CORS, then setting a token in a header is secure anyway, as is with any custom header value (e.g. X-Requested-With). This is because a custom header cannot be sent cross-domain in the first place, so verifying that it has transported from the client verifies that it is not from another domain already. As a defence in depth strategy, you can set it to a random value, as explained by this answer.
The random value doesn't need to come from the server, nor be signed. It just needs to be generated by a CSPRNG. If generated client-side, window.crypto should be used for this. All the server does is check that the header and cookie values match.
A third party domain cannot forge a request because even though the cookie value will be sent by the browser automatically from the victim's machine, the attacker cannot include the value in the header or the request body.
With the Synchronizer Token Pattern the CSRF token is generated server-side and stored against the session. This value has to be sent from each form submission and is verified server-side that it matches the stored token.

Related

How to use jwt authentication for static served content?

I have a site composed by a frontend (written in Vue) and a backend (written in node).
The api use the jwt authentication, so that only a logged in user can make requests to the backend.
The jwt is placed in the Authorization: Bearer xxx.
The problem comes when I have sensitive images or documents statically served such as identity cards.
Let's say I have a sensitive image statically served. Now, I could just add the jwt authentication also for that statically served image, no problem, but in the frontend side, how do I tell to the browser to put my jwt on the request?
<img href="/my/sensitive/image.png" />
Note that the jwt is not known a priori, it is retreived by the user login.
Use cookies. Store the JSON Web Token in a cookie (preferably with HTTPOnly, Secure and SameSite flags on), so that the browser automatically appends the value on every request to your origin.
This is a good idea from the security point of view, too - if client-side JS cannot access the token at any time, the risk of leaking it via a cross-site scripting vulnerability drops to zero.

Security To Implement On Persist Cookie REST Api Website / Mobile Apps

So my current state is I have a REST API web server (ASP.Net Web API), a website in plain Html which communicates with the server via ajax / angular post and get, also I have a mobile application which communicates via ajax / angular post and get.
I use Basic Auth header to secure the request, the web server will decrypt the content of the auth header and do the verification after.
What kind of attacks would the system be vulnerable to? Also what kind of security should I implement.
I read about the CSRF attacks and I think my system have no protection against it, but I have no idea how to implement it on REST API.
Also what about the cookie stealing attacks. Because my system uses persist cookies to store the auth token, how to deal with this kind of attack?
To prevent CSRF attacks, both your backend (ASP.NET Web API) and frontend (Angular) must be configured to prevent such an attack.
Taken from https://angular.io/guide/security#xsrf:
To prevent XSRF, the application must ensure that a user request originates from the real application, not from a different site. The server and client must cooperate to thwart this attack.
In a common anti-XSRF technique, the application server [backend] sends a randomly generated authentication token in a cookie. The client code reads the cookie and adds a custom request header with the token in all subsequent requests. The server compares the received cookie value to the request header value and rejects the request if the values are missing or don't match.
This technique is effective because all browsers implement the same origin policy. Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site. That means only your application can read this cookie token and set the custom header. The malicious code on evil.com can't.
With that in mind, here's another quote from Angular HttpClient Docs which explains how you can implement it.
Taken from https://angular.io/guide/http#security-xsrf-protection:
When performing HTTP requests, an interceptor reads a token from a cookie, by default XSRF-TOKEN, and sets it as an HTTP header, X-XSRF-TOKEN. Since only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
By default, an interceptor sends this header on all mutating requests (POST, etc.) to relative URLs but not on GET/HEAD requests or on requests with an absolute URL.
your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the X-XSRF-TOKEN HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security.
Key points to take note would be:
When the angular app is loaded, it should make an API call first to your backend to retrieve an authentication token that is saved as a cookie that with the name "XSRF-TOKEN". Probably somewhere on root component (app.component.ts) ngOnInit() sounds like a good place.
By default, the authentication token will be automatically injected in the http header on all mutating requests such as POST. (Take note of this though, it is undocumented: Angular 6 does not add X-XSRF-TOKEN header to http request). Unless you return a custom-named cookie, then you have to use Angular's HttpClientXsrfModule.
With that in mind, your ASP.NET Web API should also be validating the XSRF-TOKEN as it receives requests.
With regards to your second question, cookie hijacking is done via XSS.
XSS vulnerabilities generally occur when an application takes user input and outputs it to a page without validating, encoding or escaping it.
Angular by default sanitizes inputs for tags. However, this is provided you do things "the angular way". If you use third-party libs, such as jQuery, to manipulate the DOM instead of using Angular's renderer2 module, you might lose this protections.
Taken from: https://angular.io/guide/security#xss:
In the same way, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations. Avoid directly interacting with the DOM and instead use Angular templates where possible.
For cases where this is unavoidable, use the built-in Angular sanitization functions. Sanitize untrusted values with the DomSanitizer.sanitize method and the appropriate SecurityContext.
To increase security, you should also sanitize any mutating requests (such as PUT or POST) in your backend.
It is difficult to provide you with code examples because your question seem to be a more theory-based question.
I hope you will take a read on those links that I have hyperlinked above. They are definitely more detailed and well-explained. I hope it will at least point you in the right direction of what to get started on.

Is it secure to send username and password in a Json object in the body of a post request?

I am building a web application and my web server is secure, meaning that it uses an ssl cert with the front end to encrypt the connection.
When a user logs in, a JSON object which looks like this is created, and sent to the server.
{
username:"the user's username",
password:"the user's password"
}
On the server this is verified with a hashing algorithm that uses a salt. Once it is verified an api token is created which is valid for a certain amount of time, and is passed back and forth in the header in order to verify the user when requests are being made. Is sending the username and password like this best practice/secure, or is it better to send it in the header?
Lets divide it to many points:
1) you use a valid SSL certificate to secure the communication between the user and the server (It must be valid)
2) Sending the username and password in the body of the POST request is the best practice (Never use GET to send sensitive information such as Credentials)
3) Sending the api token in the HTTP request and response headers is the best practice (Again never use GET to send sensitive information such as session tokens)
So based on the points above, it seems that there is no risk in this implementation but you need to take the following points in your consideration:
1) The time out of the API token should be short in case of idle user. (5 ~ 15 mins are the averages based on the criticality of the application)
2) The length of the API token should be long string approx. 30 ~ 40 characters.
3) The API token generation must be randomized and hard to predict to protect from (session prediction attacks.)
Hope this help you.
What you are describing is basically HTTP basic authentication.
Is sending the username and password like this best practice/secure, or is it better to send it in the header?
In security point of view I cannot think of a big difference whether you send the credentials in the body or in the header. Basically whoever manages to read the clear text message, can see the credentials in both components. The common practice when using the basic authentication is to use the HTTP header though:
Authorization: Basic VGVzdFVzZXI6UGFzc3dvcmQxMjM0
where VGVzdFVzZXI6UGFzc3dvcmQxMjM0 is your base64-encoded credentials. The decoded string in this case is: TestUser:Password1234
It is important to realize that in your case the TLS is the only protection for the credentials in transit so you must identify all the nodes in the communication channel that could potentially expose the clear message. For example if you are using proxies that would terminate the TLS, those proxies are potential vectors for MITM attacks.
If you want to increase the security for the credentials in transit, one option could be to implement asymmetric end-to-end encryption so that you would encrypt the credentials with an authenticated public key on the client-side (e.g. certificate signed by a trusted CA) and then decrypt it at the destination with the private key known only for your server. In this case you would not need to worry too much what happens to the message in-transit.

Is it ok to store user credentials in the JWT

Is it ok to store user credentials (username / password) in the JWT (so sign it and verify the resulted token later)?
I heard that
No, it is not secure to send a password in a JWT. This is because the
JWT claims are simply encoded and can easily be decoded by anyone that
sees them. It is not secure to store any sensitive information in a
JWT that returned to a user
but I don't know why does the JWT website recommends using it for authentication purposes then:
When should you use JSON Web Tokens?
Here are some scenarios where JSON Web Tokens are useful:
Authentication: This is the most common scenario for using JWT. Once
the user is logged in, each subsequent request will include the JWT,
allowing the user to access routes, services, and resources that are
permitted with that token. Single Sign On is a feature that widely
uses JWT nowadays, because of its small overhead and its ability to be
easily used across different domains
The JWT is the result of the authentication. For example
User sends his credentials (e.g. username/password) to an authentication service. It could be a third party one or one inside your monolith or your own microservices dedicated to authentication.
The service validates username-password. If authentication success it returns an JWT that represents that the user is already authenticated, in other words he is who claim he is. This JWT could contain a payload without sensitive information (don't store the password here).
The user sends another request to a service business with the JWT. If the JWT isn't expired and is not corrupted (the sign is still valid) then the service could trust in its JWT. Maybe this task will be delegated to an authorization service.
What is inside the JWT token?
Well, the simplest JWT contains information about the sign (I can't enter in much detail here because I'm not a security expert) that allows to check if the sign has been corrupted when a request with the JWT is received.
This information can be verified and trusted because it is digitally signed
Besides that, the JWT allows to send a payload.
More formally, the JWT is composed by:
Header: type of the token + hashing algorithm being used
Payload: Claims are statements about an entity (typically, the user) and additional metadata.
Signature: The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
For example, if I send a request to a authentication service with my credentials username:password being gabriel:giussi, it will check these credentials and if they're OK it could create the following JWT:
Then with every request I will then the encoded JWT that contains my username and the service will
Perform authorization (What Gabriel is authorized to do?) if the JWT sign is valid.
Ask me to login again if the JWT has expired
Return an authentication error if the sign is broken.
Shortly: yes, it is OK to pass/receive sensitive data in JWT if you encrypt the data before placing into JWT's payload and decrypt it after the JWT validation to use it.
In a general case you would not need to keep user credentials in the JWT because the JWT is by itself a dynamically generated credential that represents the login / password (or the other means of authentication) provided at the JWT's first generation time.
1.1 You could however pass something that is not as sensitive as pure login / password but still bears the valuable information you need at the JWT validation time. It can be user ID (in a sub claim, hashed if desired), or access level code or the like.
Nevertheless if you wish you can pass the sensitive information with JWT. And this is all pretty easy as per below.
2.1 For sensitive data you could use your specific private claims in the JWT's payload, e.g.:
{
// These are registered claims: (see https://www.rfc-editor.org/rfc/rfc7519#section-4.1)
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
// There can be some public claims you are not afraid to expose to the world
// these are omitted here for brevity (see https://www.rfc-editor.org/rfc/rfc7519#section-4.2).
"omitted": "for brevity",
// And here can go some private claims you wish to include in the payload, e.g.:
"sensitiveInfo": {
"username": "admin",
"password": "12345",
"account_balance": 10000,
"etc": "something else"
}
}
2.2 The sensitiveInfo payload key by default is only base64-encoded (so it is easily read by anyone who gets the JWT). To make it secure you can encrypt it with some external module (e.g. crypto or bcrypt on NodeJS or PHP's techniques of your choice).
2.3 In this case:
At the JWT generation step you have to encrypt the key's data before you provide the entire payload to JWT generator.
At the JWT validation step, after the JWT successfully passes the standard validation (e.g. jsonwebtocken jwt.verify() in Node) you get the decoded payload with encrypted data in sensitiveInfo key. You now just have to decrypt the data and use it as you planned.
This is it.
You should use jwt only to store a token which your API will consume. The token will be generated after a successful login and it can be attached to any request sent to your API and all request should be proceeded only if the token is valid.

Why should I leave JSON Web Token payload nonencrypted?

I'm reading on JWT, there are so many tutorials and so many approaches, it's confusing.
I have couple of questions regarding proper usage of JWTs:
1) I keep seeing inconsistent means of transporting JWTs to and from the server. For example, here: one transport method for retrieving the token (via JSON-encoded object in POST body), another method for submitting it (via HTTP header). Why such inconsistency? Of course, it's up to the implementer to choose the methods, but wouldn't it be good practice at least to be consistent and use either only header or only body?
2) The JWT payload contains the information of state because the server is not maintaining it. It is obvious one should keep the size of the payload as small as possible, because the size of JWT is added to every request and response. Perhaps just a user id and cached permissions. When the client needs any information, it can receive it via (typically JSON-encoded) HTTP body and store it in the local storage, there seems to be no need to access the read-only JWT payload for the same purpose. So, why should one keep the JWT payload nonencrypted? Why mix the two ways of getting application data to the client and use both JWT payload and normal data-in-response-body? Shouldn't the best practice be to keep JWT always encrypted? It can be updated only on the server side anyway.
1) I keep seeing inconsistent means of transporting JWTs to and from the server. [...] wouldn't it be good practice at least to be consistent and use either only header or only body?
This may depend on the Client. While a web app can get a higher degree of security by storing the JWT in cookie storage, native apps may prefere local storage in order to access the JWT information. [1]
2) The JWT payload contains the information of state because the server is not maintaining it. It is obvious one should keep the size of the payload as small as possible, because the size of JWT is added to every request and response. Perhaps just a user id and cached permissions. When the client needs any information, it can receive it via (typically JSON-encoded) HTTP body and store it in the local storage, there seems to be no need to access the read-only JWT payload for the same purpose.
The JWT keeps the Backend state, not the client state. The Backend state may be that User 128 is logged in as administrator. This is (in my example) stored in the JWT in the fields Subject and Scopes. Instead of the client sending an ID of a Backend session that contains this information, the info is in the JWT directly. The backend does thus not have to keep a session that stores the logged in state of user 128. If the Client requests information of User 2, the BE may decide that this info is forbidden if the JWT tells that the logged in user has ID 1.
So, why should one keep the JWT payload nonencrypted?
The state is normally not secret to the client. the client cannot trust the information in the JWT since it does not have access to the secret key that is used to validate the JWT, but it can still adjust the GUI etc from the information in the JWT. (Like showing a button for the admin GUI or not.)
Why mix the two ways of getting application data to the client and use both JWT payload and normal data-in-response-body?
See above, the main purpose of the JWT is to keep information the the Backend, not the Client. Once the user loggs in, the Backend ask "Hey, can you hold this info for me and attach it to every request so that I can forget about you in the meantime?" Like if your manager asks you to wear a name sticker on your skirt so that he/she don't have to remember your name. :-) (And he/she signs it so that you cannot alter it without him/her noticing.
Shouldn't the best practice be to keep JWT always encrypted? It can be updated only on the server side anyway.
It doesn't really bring any security unless you store secret information in the JWT, and that bay be better to do server side. The decryption is a bit more cumbersome to decrypt compared to just verifying a signature.
[1] Local Storage vs Cookies