Authentication and Authorisation 101
Tags: javascript, beginners, security
Published: 2021-01-16 18:18:39

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k3er9yend19vj5sxhttu.png)

_This blog post was originally published in Tes Engineering blog [here](https://engineering.tes.com/post/authentication-and-authorisation)._

Last year I gave a talk at a [Node Girls](https://nodegirls.com/) and [Women of Security](https://wearetechwomen.com/wosec-women-of-security/)
meetup to share a few things I have learned about authentication and authorisation since joining our [Security Engineering team at Tes](https://engineering.tes.com/post/tes-eng-sec-team/).
You can see the video of this talk [here](https://youtu.be/dF19VrneJGo).

This post summarises some of the key points made during the talk, alongside some sketch notes and code snippets from [an example app](https://github.com/cfereday/pet-shop/tree/master/shop).

Authentication and authorisation both relate to the concept of identity. Though the words are similar their meanings are different. Let’s explore how...

### Authentication
At the most basic level, we can say that authentication is the process of checking the identity of a user: _are you who you say you are?_

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fhj9yddsyl8unrfkzpej.jpg)

The most common place that authentication is used is the Login Page of an application. During login user entered credentials are checked against what we have stored in the database. This allows us to verify that we know and trust a user is who they say they are, via, for example, a username and a password.

Although the concept of authentication is straightforward, the technical process of its implementation is typically complex, because it’s absolutely vital to keep users’ data secure. For this reason, many companies opt to use a third party company, for example Google or Auth0, to handle the authentication process for them.

Some companies choose to implement authentication themselves. Here are a couple of golden rules if you go down this route.

#### Rule 1: Only a customer should know their password

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lfxxydyv4bm8uw7z0h3y.jpg)

Keeping secret data secure is vitally important for any company to protect their users and their reputation. We want to mitigate against the risk that even if a bad actor got access to a database, they would never get a plain text password. The safest strategy to prevent this is to not store the plain text password at all.

One solution is to hash passwords to carry out a ‘one way’ transformation which turns turns a plain text password into an unrecognisable string. We can use one way encryption to verify the password whilst making it very difficult for a bad actor to transform it to its original plain text value.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hj5r38k6gbecpxf2l3st.png)

We can safely hash passwords by using well maintained and recognised open source libraries, such as [bcrypt library](https://www.npmjs.com/package/bcrypt). Here’s an example code snippet using the [bcrypt library](https://www.npmjs.com/package/bcrypt) to hash a password before storing it, to keep user credentials safe.

#### Rule 2: Always validate user input before using it
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/db1hktzyvnulrzushn1y.jpg)

One of the most common places for an attack on an application is the Login page. Injection or hijacking attacks can aim to make our code do something we did not tell it to do, by sending an instruction where we would expect some user-entered data or credentials.

Never trust the user input to safeguard applications, but rather always validate and transform data before using it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3aqb1h0mnllgzynb8fon.png)

Again a widely used open source validation library like [Joi](https://github.com/hapijs/joi) can help you easily create schemas and transform the data into safe objects.

### Authorisation
After a user has been authenticated, we can move onto checking what resource they are authorised to access. It's important to control who-can-access-what to protect data, reputation and revenue.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/l2jvf3sopq5p5ujydqts.png)

We can use roles to indicate whether or not a user should have access to a resource. For instance, only an administrator should be able to access the admin page, or only a particular client has access to a specific endpoint.

#### JSON Web Tokens(JWT)
[Json Web Tokens (JWT)](https://jwt.io/) help to implement authorisation.
JWT is an open standard that defines a way to securely transmit information between parties as a JSON object. 

We can trust this information because it is digitally signed and verified by server-side code.
It helps authorisation systems scale, to ensure only those authorised have access to particular resources, and protect private personal data.

#### Sign
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kdkvc1pdx6y1abto8uur.jpg)

A JWT is digitally signed with a secret or a public/private key pair that is only known to an application. This means an application can ensure that the JWT was signed from a trusted source (via said secret or corresponding public key) and prevents it from being secretly tampered with.

Here’s an example of using the [jsonwebtoken library](https://www.npmjs.com/package/jsonwebtoken) to sign a JWT where it is then added to a cookie.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qk8p5lmavxhn1s3os8vp.png)

Role data is included as part of the JWT, for instance in this example if the username is ‘admin’ then this user gets an ‘admin’ role. Clearly this management of roles is a hack for a toy project, in a real secure system there will be more sophisticated ways of managing admins.

#### Verify
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/73wnxk3vqpwa3shz06gn.jpg)

Once we have a JWT, we can verify that the token is valid on our servers, and only trust it if the JWT hasn’t been tampered with or expired.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lggtypka2yhta4kvg5ba.png)

The [jsonwebtoken library](https://www.npmjs.com/package/jsonwebtoken) allows us to digitally verify a user or client and effectively manage whether they should have access to a particular resource.

### Summary
Aside from learning more about authentication and authorisation, the aim of this blog is to show that as engineers we can learn a few good security practices and have access to many open source libraries to help us build more secure applications.

Writing secure code is absolutely critical for our users - you don’t need to be a security expert to get started.

If you’d like to learn more about some of the topics touched on here, I've listed below some articles that I found useful.

### Further Reading

##### Passwords
* [Passwords and Jargon: The Guardian](https://www.theguardian.com/technology/2016/dec/15/passwords-hacking-hashing-salting-sha-2)
* [OWASP Password storage cheat sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
* [Bcrypt](https://www.npmjs.com/package/bcrypt)

##### Validation
* [Cross-Site Scripting](https://www.google.com/about/appsecurity/learning/xss/index.html)
* [The most common XSS in React JS applications](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0)
* [Hapi/joi](https://www.npmjs.com/package/@hapi/joi)


##### JSON web token
* [Open Standards](https://tools.ietf.org/html/rfc7519)
* [JWT](https://jwt.io/introduction/) and [JWT is awesome](https://thehftguy.com/2020/02/18/jwt-is-awesome-heres-why/amp/)
* [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)

##### Cookies
* [Mozilla](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) and [Cookie Flags](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/Cookie)
* [OWASP Secure Cookie Flag](https://owasp.org/www-community/controls/SecureFlag)
* [Http Only Flag](https://owasp.org/www-community/HttpOnly)
* [Session vs Persistent Cookies](https://www.allaboutcookies.org/cookies/cookies-the-same.html)