Basics of Authentication
Basics of Authentication
What is Authentication?
Authentication is the process of verifying someone’s identity. A real-
world example of that would be when you board a plane, the airline
worker checks your passport to verify your identity, so the airport
worker authenticates you.
If we talk about computers, when you log in to any website, you
usually authenticate yourself by entering your username and
password, which is then checked by the website to ensure that you
are who you claim to be. There are two things you should keep in
mind:
Authentication is not only for the persons
And username and password are not the only way to
authenticate.
Some other examples are:
When you open a website in the browser. If the website uses HTTP,
TLS is used to authenticate the server and avoid the fake loading of
websites.
There might be server-to-server communication on the website. The
server may need to authenticate the incoming request to avoid
malicious usage.
1
How does Authentication Work?
On a high level, we have the following factors used for
authentication.
Username and Password
Security Codes, Pin Codes, or Security Questions
An example would be the pin code you enter at an ATM to
withdraw cash.
Hard Token and Soft Tokens
Hard tokens are the special hardware devices that you attach to
your device to authenticate yourself. Soft tokens, unlike hard
tokens, don’t have any authentication-specific device; we must
verify the possession of a device that was used to set up the
identity. For example, you may receive an OTP to log in to your
account on a website.
Biometric Authentication
In biometric authentication, we authenticate using biometrics such
as iris, facial, or voice recognition.
We can categorize the factors above into three different types.
Username / Password and Security codes rely on the person’s
knowledge: we can group them under the Knowledge Factor.
In hard and soft tokens, we authenticate by checking the possession
of hardware, so this would be a Possession Factor.
And in biometrics, we test the person’s inherent qualities, i.e., iris,
face, or voice, so this would be a Qualities Factor.
This brings us to our next topic: Multi-factor Authentication and
Two-Factor Authentication.
2
Multifactor Authentication
Multifactor authentication is the type of authentication in which we
rely on more than one factor to authenticate a user.
For example, if we pick up username/password from
the knowledge factor. And we pick soft tokens from
the possession factor, and we say that for a user to authenticate,
they must enter their credentials and an OTP, which will be sent to
their mobile phone, so this would be an example of multifactor
authentication.
In multifactor authentication, since we rely on more than one factor,
this way of authentication is much more secure than single-factor
authentication.
One important thing to note here is that the factors you pick for
authentication, they must differ. So, for example, if we pick up a
username/password and security question or security codes, it is
still not true multifactor authentication because we still rely on the
knowledge factor. The factors have to be different from each other.
Two-Factor Authentication
Two-factor authentication is similar to multifactor authentication.
The only difference is that there are precisely two factors in 2FA. In
MFA, we can have 2, 3, 4, or any authentication factors; 2FA has
exactly two factors. We can say that 2FA is always MFA, because
there are more than one factors. MFA is not always 2FA because
there may be more than two factors involved.
Next we have the difference between authentication and
authorization. This comes up a lot in the interviews, and beginners
often confuse them.
3
What is Authentication
Authentication is the process of verifying the identity. For example,
when you enter your credentials at a login screen, the application
here identifies you through your credentials. So this is what the
authentication is, the process of verifying the identity.
In case of an authentication failure, for example, if you enter an
invalid username and password, the HTTP response code is
“Unauthorized” 401.
What is Authorization
Authorization is the process of checking permission. Once the user
has logged in, i.e., the user has been authenticated, the process of
reviewing the permission to see if the user can perform the relevant
operation or not is called authorization.
And in case of authorization failure, i.e., if the user tries to perform
an operation they are not allowed to perform, the HTTP response
code is forbidden 403.
Authentication Strategies
Given below is the list of common authentication strategies:
Basics of Authentication
Session Based Authentication
Token-Based Authentication
JWT Authentication
OAuth - Open Authorization
Single Sign On (SSO)
4
HTTP Basic Authentication
Our last guide was about the basics of authentication, where we
discussed authentication, authorization, types of authentication,
authentication factors, authentication strategies, and so on.
In this guide today, we will be learning about basic authentication,
and we will see how we can implement Basic Authentication in
Node.js.
What is Basic Authentication?
Given the name “Basic Authentication”, you should not confuse
Basic Authentication with the standard username and password
authentication. Basic authentication is a part of the HTTP
specification, and the details can be found in the RFC7617.
5
Now that we know what basic authentication is, the question is, how
does it work? The answer is: it is controlled by the response of the
server.
Step 1
When the browser first requests the server, the server tries to check
the availability of the Authorization header in the request. Because it is
the first request, no Authorization header is found in the request. So
the server responds with the 401 Unauthorized response code and also
sends the WWW-Authenticate header with the value set to Basic, which
tells the browser that it needs to trigger the basic authentication
flow.
If you notice the response, we have an additional parameter called
realm, which is just a value assigned to a group of pages that share
the same credentials.
The browser might use Realm to cache the credential. In the future,
when there is an authentication failure browser will check if it has
the credentials in the cache for the given realm of the domain, and
it may use the same credentials.
Step 2
6
Upon receiving the response from the server, the browser will notice
the WWW-Authenticate header and will show the authentication popup.
Step 3
After the user submits the credentials through this authentication
popup, the browser will automatically encode the credentials using
the base64 encoding and send them in the Authorization header of the
same request.
Step 4
Upon receiving the request, the server will decode and verify the
credentials. If the credentials are valid, the server will send the
response to the client.
So that is how Basic Authentication works.
//src/auth.js
7
const base64 = require(‘base-64’);
function decodeCredentials(authHeader){}
8
Session Based Authentication
Learn what is Session Based Authentication and how to implement
it in Node.js.
HTTP is the internet protocol that standardizes how clients and
servers interact with each other. When you open a website, among
other things, HTTP is the protocol that helps load the website in the
browser.
HTTP is Stateless
HTTP is a stateless protocol which means that each request made
from the client to the server is treated as a standalone request;
neither the client nor the server keeps track of the subsequent
requests. Sessions allow you to change that; with sessions, the
server has a way to associate some information with the client so
that when the same client requests the server, it can retrieve that
information.
In this guide, we will learn what is Session-Based Authentication and
how to implement it in Node.js.
What is Session-Based Authentication?
Session-based authentication is a stateful authentication technique
where we use sessions to keep track of the authenticated user. Here
is how Session Based Authentication works:
User submits the login request for authentication.
Server validates the credentials. If the credentials are valid, the
server initiates a session and stores some information about the
client. This information can be stored in memory, file system, or
database. The server also generates a unique identifier that it can
later use to retrieve this session information from the storage.
Server sends this unique session identifier to the client.
9
Client saves the session id in a cookie and this cookie is sent to the
server in each request made after the authentication.
Server, upon receiving a request, checks if the session id is present
in the request and uses this session id to get information about the
client.
And that is how session-based authentication works.
Session-Based Authentication in Node.js
Now that we know what session-based authentication is, let’s see
how we can implement session-based authentication in Node.js.
Please note that, for the sake of simplicity, I have intentionally kept
the project strictly relevant to the Session Based Authentication and
have left out a lot of details that a production-ready application
may require. Also, if you don’t want to follow along,
project codebase can be found on GitHub.
First things first, create an empty directory that will be holding our
application.
mkdir session-auth-example
10
const app = express();
app.use(
sessions({
secret: ‘some secret’,
cookie: { maxAge: 1000*60*60*24, //24 hours},
resave: true,
saveUninitialized: false,
}))
app.use(express.json());
app.use(express.urlencoded({extended:true}));
//@todo register routes
app.listen(3000,() => {console.log(‘Server Running at port 3000’);});
Creating Handlers
Create a directory called the handlers at the project’s root. This is the
directory where we will be placing all the route-handling functions.
Now let’s create the homepage route, which will show the welcome
message and a link to log out for the logged-in users and redirect to the
login screen for the logged-out users. Create a file at handlers/home.js with
the following content.
11
<h1>Welcome back ${req.session.userid}<h1>
<a href=”/logout”>Logout</a>
`);
res.end();
};
req.session.userid.req.session
is automatically populated using the session cookie by the
express-session middleware that we registered earlier. req.session.userid is
one of the data fields that we will set to store the userid of the logged in
user.
Next, we need to register this handler with a route. Open the index.js file at
the root of the project and register the following route:
Next, we have the login page, redirecting the user to the home screen if the
user is logged in or showing the login form. Create a file at
handlers/login.js with the following content:
12
res.end();
};
Again, at the top of the function, we are simply checking if we have userid in
the session (which means the user is logged in). If the user is logged in, we
redirect them to the homepage; if not, we show the login screen. In the
login form, we have the method of post, and we submit the form to process-
login. Please note that, for the sake of simplicity, we have a simple HTML
string returned in the response, but in a real-world application, you will
probably have a separate view file.
Let’s first register this page and then implement /process-login endpoint.
Open the index.js file from the root of the project and register the following
route:
As you can see, we are simply checking that the username and password
should both be admin and admin for a user to authenticate successfully.
Upon finding valid credentials, we set the userid in the session by updating
req.session.userid. Similarly, you can set any data in the session. For example,
if we wanted to store the user role, we would do the following:
req.session.role=’admin’;
And later access this value out of the session anywhere in the subsequent
requests. Register this route in the index.js file at the root of the project:
13
app.post(‘/process-login’, ProcessLoginHandler);
“scripts”:
{
“start”: “node index.js”
},
Now you can start the application by running the following command:
14