HTTPS or JWT for authentication? - node.js

I'm going to implement my authentication method using JWTs in node js.
I was searching a while for different methods of authentication and finally decide to use JWTs.
However I am confused about the JWT based authentication.
Here's my question : Should we send our JWT over HTTPS? if yes, then why should we use JWT at all ? and why not sending all needed information over HTTPS without JWT ?
In other words when there is security issues without HTTPS (like man-in-the-middle attack), what is the reason of using JWT for authentication purposes? is there any other authentication approach which works perfectly without using HTTPS?

Here you are mixing two different protocol levels.
HTTPS (or rather TLS - transport level security) is a transport layer - data transport pipe ensuring you communicate with a legitimate server and that nobody could read or change the data exchanged. HTTPS doesn't care about data itself (e. g. authentication)
JWT is commonly used as part of the payload (data itself) describing client's identity and other attributes.
Most commonly you need both - JWT to ensure authentication or authorization and TLS/HTTPS to ensure that nobody could steal or change your JWT token or data.
HTTPS could provide client authentication, but the client needs to have its client keypair and certificate which is not really free or easy to manage (e. g. this is how electronic ID cards work or I see it often in the server-to-server scenarios).

To expand on #gusto2
JWT and HTTPS accomplish different goals. Three major components of security systems.
C - Confidentiality - Is data secure from outsiders reading it?
I - Integrity - Is data secure from outsiders tampering with it?
A - Authenticity - Is data sent from the proper person
HTTPS ensures confidentiality and integrity.
JWT helps with authenticity. However, it is your job to ensure that tokens
are valid. This is not provided out of the box.

“and why not sending all needed information over HTTPS without JWT ?”
I think the main point is that Restful or API based interaction is stateless. So in all interaction server needs to get the token to know the authenticity. And for authenticity that all requests are coming from logged in authentic user it needs to get same JWT.
Hence answer to the question in OP as Daniel said is for Authenticity.
In normal form based request we do not use token, why? Because it is stateful and we save information in session or cookies. But APIs are stateless so some token needs to be sent.

Related

Is JWT necessary over HTTPS communication?

I'm developing a MEAN stack application, and I'm currently setting up an account system. I've seen several tutorials about Authentication, all using JWT.
I am wondering if, JWT could be used as way to secure communication transport over non-secured connection like HTTP?
I've set up HTTPS to communicate from my Angular 4 front-end to my NodeJS + Express back-end, and thus, wondering if JWT are necessary to secure my communications?
JWT should not be confused with encryption. From jwt.io:
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a
compact and self-contained way for securely transmitting information
between parties as a JSON object.
The JWT is signed with public/private key pairs so the sender can be verified, and verified that the payload has not been modified. However, the JSON Web Token is in clear text.
var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";
var payload = token.split('.')[1];
console.log('Payload: '+atob(payload))
Below is a figure from jwt.io showing the authentication flow when using JWT.
You need SSL/HTTPS to encrypt the communication. Without SSL/HTTPS attackers can sniff the network traffic and obtain the JWT, hence your application is vulnerable to man in the middle attacks.
Is JWT necessary over HTTPS communication?
No. Communication protocol (HTTP v.s. HTTPS) is one thing, and authentication mechanism (JWT v.s. Session) is another -- these are 2 totally different area.
For communication protocol (HTTP v.s. HTTPS), HTTPS can be used alone, without any JWT tokens or sessions. For example, a static web site can be made (only HTML+CSS) and served with HTTPS. In this way, the web site can be certificated by CA and prevent forge attack.
Even if you need authentication in web application, JWT token is not the only choice. Session is old technology but it is still reliable, which made JWT definitely NOT necessary.
No, JWT is not required when your server supports HTTPS.
HTTPS protocol ensures that the request & response are encrypted on the both(client & server) the ends.
I believe you would want to send across user credentials in every request to the server, and in turn server validates the user before sending any response from the server.
Although you can do the above, but on the server-end, you would end up validating user credentials against a Database in every request which is a expensive task, you can avoid this when you use JWT.
JWT basically authenticates a user once & issues an access token which could be valid for a duration of time.
Nowadays developers prefer Token-Based Authentication instead of Session. Token-Based Authentication has lots of advantages over Session.
We use JWT i.e. JSON Web Token to generate a token after user authentication, every time your front-end app makes an API call so your system should check whether the request has a valid token or not if it is there and it is valid then it is considered as the valid user.
In short, we use JWT to validate our API calls it is nothing to do with HTTP or HTTPS
I'm new to JWT. Here is my scenario of an attack of JWT when it's in the http instead of https. Suppose a JWTa is issued to userA for accessing resource A on the server. A hacker is also a legal user of the server, he got JWTh to access resource H. Without the https protection, the hacker can sniffer the network and get the JWTa in the http header from A's request and put it into the hacker's request. Since JWTa is a valid token, so the hacker can access resource A. I guess the JWT protocol can prevent this, but I don't know how. After the signature is verified, the claim also needs to be verified. Seems the "aud" can prevent this, but I don't know how it works exactly.

Technique to detect request modification on server side using JWT

I want to know a technique with which server can identify if data coming in the request is not modified by an attacker. We are having REST APIs on server side which will be invoked from a mobile app client or a browser. I was thinking of using JWT (JSON Web Tokens). But not sure how it will achieve this. People have used JWT for session management purpose mostly. I do not need the session management. I just want to detect the request data modification. need some help here...
It depends on what type of attacker you wangt to protect against, but the TL;DR is you don't have to do anything as any such protection is either unnecessary (with some special case exceptions as detailed below) or useless.
Protecting against a valid user modifying his own requests
There is no point in this. Any secret you would use for such protection (for signing requests, essentially) would have to be sent to the client so that it can use it to sign whatever it wants to. But if it is sent to the client, the user already has it and can use it to sign any modified request. You have to architect the application in a way that security is enforced on the server side and valid users can't forge requests that they are not supposed to make.
Protecting against a man-in-the-middle attacker
Let's suppose you want to protect requests against somebody between the user and the server. If you access the server over a secure channel (https), it already does this for you, you don't have to implement anything in addition to that.
However, I can think of special cases. First, you may be worried about intermediate proxies that terminate SSL, like for example a company proxy that serves https websites with its own certificate, set as a trusted root on company clients. This is fairly common practice, but usually you as the application developer don't want to deal with this. The other thing is when you don't want to use SSL, but I'd say it's rather a special case when you are worried about request integrity, but not about confidentiality.
Anyway, if you are in a situation where you do in fact need to maintain integrity in another way besides (or instead of) https, you could give your client a secret and sign requests with that secret, like for example using HMAC or another message authentication protocol. You would take relevant fields from request headers and also the whole request body, create an HMAC of them with the secret and attach that to the request. The server, having the same secret for the client could create the same hash and verify if the client had the secret and also that the request sent is the same as signed by the user. Note that to prevent replay attacks, you would also have to include a timestamp and/or a nonce header in the signature.
The question then is how you get this secret to the client securely, and depending on your circumstances, this can be a tricky one to solve.
Edit
I just realized you had csrf as a tag to the question. Be aware that csrf has nothing to do with modified requests, and you do have to implement protection against csrf in general.
The JSON Web Signature is a cryptographic mechanism designed to secure data with a digital signature unique to the contents of the token in such a way that we are able to determine whether the data of the token has been tampered with or not.
source: php-authorization-jwt-json-web-tokens
You can use JWT to verify client requests but the client need to request a token (at least once) before any verifiable request.
Tokens are created on server side only using a secret key (never sent to the client) used to encode/sign the token, the client can decode and access the token but doesn't modify it, just send it back as it is.

Font End secure authentication only allowed to come from a specific website

I have a private rest API. Each of our clients websites currently performs server side authentication over SSL to start an order with us. Each client has a unique client id so I can identify which client is making the request and reject any client id which doesn't exist in our system. Is there a way to do this securely from the front end of a clients website with javascript? I can't put the client id in the client code since any developer could look at the source code and figure out how to spoof requests from another site. I think checking referrer headers is not reliable as well? Would really like to know the best practice for situations like this.
Not sure if I understand your question correctly, but typically you would encode your client id as a claim in the security token issued when authenticating your users. As the security token is signed by the issuer, you can verify that the token is not modified when you receive the token on each request.
Obviously you will need to use the https protocol to prevent the token from being stolen. See here for more information.

SPA best practices for authentication and session management

When building SPA style applications using frameworks like Angular, Ember, React, etc. what do people believe to be some best practices for authentication and session management? I can think of a couple of ways of considering approaching the problem.
Treat it no differently than authentication with a regular web application assuming the API and and UI have the same origin domain.
This would likely involve having a session cookie, server side session storage and probably some session API endpoint that the authenticated web UI can hit to get current user information to help with personalization or possibly even determining roles/abilities on the client side. The server would still enforce rules protecting access to data of course, the UI would just use this information to customize the experience.
Treat it like any third-party client using a public API and authenticate with some sort of token system similar to OAuth. This token mechanism would used by the client UI to authenticate each and every request made to the server API.
I'm not really much of an expert here but #1 seems to be completely sufficient for the vast majority of cases, but I'd really like to hear some more experienced opinions.
This question has been addressed, in a slightly different form, at length, here:
RESTful Authentication
But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:
Javascript Crypto is Hopeless
Matasano's article on this is famous, but the lessons contained therein are pretty important:
https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/
To summarize:
A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
Once you have SSL, you're using real crypto anyways.
And to add a corollary of my own:
A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.
This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!
HTTP Basic Auth
First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.
This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.
The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.
This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!
The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.
HTTP Digest Auth
Is Digest authentication possible with jQuery?
A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.
Query Authentication with Additional Signature Parameters.
Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.
https://www.rfc-editor.org/rfc/rfc5849
Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?
JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.
Token
The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.
This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.
SSL Still
The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.
To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.
Token Expiry
It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.
Firesheeping
However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/
The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.
tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.
A Separate, More Secure Zone
The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?
Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.
Cookie (just means Token)
It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.
Session (still just means Token)
Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:
Users start with an unauthenticated token.
The backend maintains a 'state' object that is tied to a user's token.
The token is provided in a cookie.
The application environment abstracts the details away from you.
Aside from that, though, it's no different from Token Auth, really.
This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.
OAuth 2.0
OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."
The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."
Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.
There are two ways that OAuth 2.0 can help you:
Providing Authentication/Information to Others
Getting Authentication/Information from Others
But when it comes down to it, you're just... using tokens.
Back to your question
So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"
And the answer is: do whatever makes you happy.
The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.
I am 21 so SSL is yes
The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.
You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.
The Basic Auth / Session ID can be stolen via:
MITM attack (Man-In-The-Middle) - without SSL/HTTPS
An intruder gaining access to a user's computer
XSS
By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.
The new (more secure) flow would be:
Login
User logs in and sends login credentials to API (over SSL/HTTPS)
API receives login credentials
If valid:
Register a new session in the database Read update
Encrypt User ID, Session ID, IP address, timestamp, etc. in a JWT with a private key.
API sends the JWT token back to the client (over SSL/HTTPS)
Client receives the JWT token and stores in localStorage/cookie
Every request to API
User sends a HTTP request to API (over SSL/HTTPS) with the stored JWT token in the HTTP header
API reads HTTP header and decrypts JWT token with its private key
API validates the JWT token, matches the IP address from the HTTP request with the one in the JWT token and checks if session has expired
If valid:
Return response with requested content
If invalid:
Throw exception (403 / 401)
Flag intrusion in the system
Send a warning email to the user.
Updated 30.07.15:
JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).
I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).
Updated 17.07.16:
JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.
I would go for the second, the token system.
Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:
A lightweight and unobtrusive library for implementing token based
authentication in Ember.js applications.
http://ember-simple-auth.simplabs.com
They have session management, and are easy to plug into existing projects too.
There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.

Does an OAuth 2 client really need TLS?

I intend to build a delegated login system for an existing app. I'll be implementing both the OAuth client (in a web application) and the OAuth server (a simple authorization and resource server, that really only has a 'user' resource for now.)
With that in mind, I came across the following section in the current OAuth 2 draft (version 22):
3.1.2.1. Endpoint Request Confidentiality
If a redirection request will result in the transmission of an
authorization code or access token over an open network (between the
resource owner's user-agent and the client), the client SHOULD
require the use of a transport-layer security mechanism.
Lack of transport-layer security can have a severe impact on the
security of the client and the protected resources it is authorized
to access. The use of transport-layer security is particularly
critical when the authorization process is used as a form of
delegated end-user authentication by the client (e.g. third-party
sign-in service).
This specifically warns me that I should be using TLS on the client. We will be using HTTPS on the server, of course, but enabling HTTPS on all clients will be difficult if not impossible.
From my limited understanding of security, I imagine someone could steal the authorization grant. This brings me to my question:
Won't client authentication (using the client secret) prevent an eavesdropper from using the authorization grant? (Because the malicious party won't know the client secret, hopefully.)
If it doesn't, or if there's another attack vector here I'm not seeing, is there anything I can do to make this work securely without HTTPS on the clients? Would, for example, OAuth 1 help? (Perhaps because it has the additional request token step.)
P.S.: I was planning on doing client authentication using TLS client certificates, rather than secrets, if that makes the situation any better.
I think you are misinterpreting part of this warning. This OAuth warning is addressing OWASP A9 violations. This is saying that even though you are using OAuth you still need a secure transport layer to communicate with the client. The client doesn't require a key pair for authentication, OAuth is the client's form of authentication. However, the browser still authenticates with your application using a session id stored as a cookie value. The concern is that if an attacker is able to intercept this value, then he will have the same access as the victimized client.

Resources