0% found this document useful (0 votes)
16 views

Basics of Authentication

Uploaded by

Tariq Rashid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Basics of Authentication

Uploaded by

Tariq Rashid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Basics of Authentication

Today, we are kicking off a similar series for Authentication


strategies where we will discuss everything you need to know about
authentication and authentication strategies.
In this guide today will be talking about what authentication is, and
we will cover some terminology that will help us later in the series.
You can watch the video below or continue reading this guide.

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.

Because it is a part of the HTTP specifications, all the browsers have


native support for “HTTP Basic Authentication”. Given below is the
screenshot from the implementation in Google Chrome.
How does it Work?

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.

Basic Authentication in Node.js


I have prepared the sample project in Node.js, which can be found
on GitHub kamranahmedse/node-basic-auth-example. If you look
at the codebase of the project, we have two files index.js with the
following content:
//src/index.js

const express = require(‘express’);


const authMiddleware = require(‘./auth’)
const app = express();
const port = 3000;
//This middleware is where we have the basic authentication implementation
app.use(authMiddleware);
app.get(‘/’, (req, res) => {res.send(‘Hello World!’);});
app.listen(port, () => {console.log(`App running @ http://localhost:${port}`);});

As you can see, it’s just a regular express


server. authMiddleware registration is where we have all the code
for “Basic Authentication”. Here is the content of the middleware:

//src/auth.js

7
const base64 = require(‘base-64’);
function decodeCredentials(authHeader){}

module.exports = function (req, res, next)


{
//Take the header and decode credentials
const [username, password] = decodeCredentials(req.headers.authorization || ‘’);
//Verify Credentials
if(username === ‘admin’ && password === ‘admin’)
{return next();}
//Respond with authenticate header on auth failure
res.set(‘WWW-Authenticate’, ‘Basic realm=”user_pages”’);
res.status(401).send(‘Authentication required.’);
};

And that is how the basic authentication is implemented in Node.js.

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

Now run the following command to setup a sample package.json file:


npm init -y

Next, we need to install the dependencies:


npm install express express-session

expressis the application framework, and express-session is the package


that helps work with sessions easily.
Setting up the server
Now create an index.js file at the root of the project with the
following content:
const express = require(‘express’);
const sessions = require(‘express-session’);

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’);});

The important piece to note here is the express-session middleware


registration which automatically handles the session initialization, cooking
parsing and session data retrieval, and so on. In our example here, we are
passing the following configuration options:
 secret: This is used to sign the session ID cookie. Using a secret that
cannot be guessed will reduce the ability to hijack a session.
 cookie: Object containing the configuration for session id cookie.
 resave: Forces the session to be saved back to the session store, even
if the session data was never modified during the request.
 saveUninitialized: Forces an “uninitialized” session to be saved to the
store, i.e., saves a session to the store even if the session was not
initiated.
Another important option is store which we can configure to change
how/where the session data is stored on the server. By default, this data is
stored in the memory, i.e., MemoryStore

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.

module.exports = function HomeHandler(req, res)


{
if(!req.session.userid) {return res.redirect(‘/login’);}
res.setHeader(‘Content-Type’, ‘text/HTML’);
res.write(`

11
<h1>Welcome back ${req.session.userid}<h1>
<a href=”/logout”>Logout</a>
`);
res.end();
};

At the top of this function, you will notice the check

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:

const HomeHandler = require(‘./handlers/home.js’);


app.get(‘/’, HomeHandler);

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:

module.exports = function LoginHandler(req, res)


{
if(req.session.userid) {return res.redirect(‘/’);}
res.setHeader(‘Content-Type’, ’text/HTML’);
res.write(`
<h1>Login</h1>
<form method=”post” action=”/process-login”>
<input
type=”text”
name=”username”
placeholder=”Username”
/>
<br>
<input
type=”password”
name=”password”
placeholder=”Password”
/>
<button type=”submit”>Login</button>
</form>
`);

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:

const LoginHandler = require(‘./handlers/login.js’);


app.get(‘/login’, LoginHandler);

Next, we have to implement the functionality to process the login form


submissions. Create a file at handlers/process-login.js with the following
content:

module.exports = function processLogin(req, res)


{
if(req.body.username !== ‘admin’ || req.body.password !== ‘admin’)
{return res.send(‘Invalid username or password’);}
req.session.userid = req.body.username;
res.redirect(‘/’);
}

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:

const ProcessLoginHandler = require(‘./handlers/process-login.js’)

13
app.post(‘/process-login’, ProcessLoginHandler);

Finally, we have the logout functionality. Create a file


at handlers/logout.js with the following content:

module.exports = function Logout(req, res)


{req.session.destory(); res.redirect(‘/’);};

We reset the session by calling req.session.destroy() and then redirecting the


user to the homepage. Register the logout handler in the index.js file using
the following:

const LogoutHandler = require(‘./handlers/logout.js’);


app.get(‘/logout’, LogoutHandler);

Running the Application


Open the package.json file and register the start script as follows:

“scripts”:
{
“start”: “node index.js”
},

Now you can start the application by running the following command:

npm run start

Now, if you open up your browser and visit the project at


http://localhost:3000 you will be able to see the Session-Based Authentication
in action.

14

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy