Web Application Authentication: How It Works and How to Implement It

In this guide, you'll learn more about how authentication in web app works and how to implement it with Authgear.

 min. read
Published on
June 24, 2022

As a web developer, you know how common it is to have authentication in your application as a requirement. And why not? It should be important, we surely want to know who is making requests, manage multi-transactions, and protect users' private information.

In this guide, you’ll learn all you need to know about web app authentication, how it works in your web apps, and how to integrate Authgear Web SDK with your web apps to implement authentication quickly and securely.

Before we start discussing all the technical details of how authentication works in web apps, let's first understand what authentication actually is with an example.

What's Authentication?

In simple terms,

Authentication is the process of verifying the identity of a user or information.

This means it is used to prove that some fact or some document is genuine, true or valid. What happens is that a user confirms their identity by providing their credentials. This piece of information is shared between the user and the service or system where authentication is required.

For example, when you want to access your Gmail account from a new device, you will need to be authenticated before you can see all of your emails or create a new one. You must prove that you own the correct login credentials by entering a username/email and password combination. When these values match with the ones stored in Google's database, you will be authenticated and granted access to the mail service.

Now that we have a clear idea of what authentication means, let's try to understand how this process actually works under the hood in web applications.

Authentication Methods in Web Applications

We have many ways in which an app can be authenticated. Let's look at each of them one by one:

Cookies are generally used to handle user authentication in web applications. Here's a diagram that shows how this works:

Working of cookie-based authentication in web apps:

A graph explaining how cookie-based authentication works in web applications.

As you can see here, the client browser sends the POST request for login credentials to the server. The server then verifies the credentials sent to it with the HTTP 200 OK status code. It creates a session ID stored in the server and returns it to the client via Set-Cookie: session=…. On the subsequent requests, the session ID from the cookie is verified in the server, and the corresponding request is processed. When you log out of the app, your session ID will be cleared from both the client and server.

Token-Based Authentication

This method is on the rise as we see more and more Single Page Applications (SPAs) being made.

One of the most common ways to implement token-based authentication is to use JSON Web Tokens (JWTs). JWTs are an open standard that defines a self-contained way to transmit information between parties as JSON objects securely.

Working of token-based authentication:

A graph showing how token-based authentication works in web applications.

When the credentials are received from the client's browser, the server validates these credentials and also generates a signed JWT containing all of the user information. The token is stateless, so it never gets stored on the server. Over the following requests, the token is passed to the server and then gets decoded in order to verify it on the server.

Third-Party Access (OAuth, API-token)

The third-party access authentication can work in two ways:

  • Via API-token: it's usually the same as we discussed above on JWT, where the token is sent to the authorization header and handled at some API gateway to authenticate the user.
  • Via Open Authentication (OAuth): as you might have guessed by its name, OAuth is an open protocol that allows secure authentication methods from the web, mobile, and desktop applications. This protocol authenticates against the server as a user.

OpenID

This is currently the most commonly used method of authentication and is more accessible to the end user. OpenID is a protocol that uses identity provider(s) to validate a user.

This allows service providers a way to achieve Single SignOn (SSO), thereby allowing users to use one set of credentials to log into several related yet independent software or systems. You might already be using several identity providers like Google, Facebook, Twitter, etc.

Security Assertion Markup Language

Security assertion markup language, or SAML, is an open standard used for authentication and is based upon the extensible Markup Language (XML) format.

Web apps use it to transfer authentication data between two parties - the identity provider (IdP) and the service provider (SP). It provides a way to achieve SSO where the user can use the identity provider URL to log into the application, which redirects back with XML data to the application page.

How Does Access Token Work on a Web App?

We hear the term "access tokens" whenever we talk about authentication. But what are these in the first place? Let's figure this out.

What Are Access Tokens?

Access token is a code used for authenticating a web application to access specific resources.

These access tokens are provided as JSON Web Tokens (JWTs), which are then passed over the secure HTTPS protocol while in transit.

They are used in token-based authentication types. When you are successfully authenticated, the web application receives an access token. Now whenever an API is called on the app, this token will be passed as a credential.

The basic structure of a web token consists of the following parts separated by dots(.):

1. Header: this again consists of two parts; the token type (like JWT) and the token signing algorithm being used (like SHA256). Here's an example:

	
{
	"alg": SHA256",
	"typ": "JWT"
}
	

2. Payload: this contains the claims. Claims are statements about an entity (like a user) with some additional data. These claims can be registered, public or private. Here's an example payload:


{
	"sub": "1234567890",
	"name": "John Doe"
	"admin": true
}

3. Signature: here, the encoded header and payload, along with a secret, the header's algorithm comes together and signs it to create a signature. For example, here's a signature code using the HMAC SHA256 algorithm:


HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

Putting it together, the output web token is three Base64-URL strings separated by dots:


eyJhbGci0iJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIi0iIxMjMONTY30DkwIiwibmFtZSI6IkpvaG4
gRG91IiwiaXNTb2NpYWwiOnRydWV9.
4pcPyMD0901PSyXnrXCjTwXyr4BsezdI1AVTmud2fU4

Working of Web Tokens

Here's how these tokens work in websites and web apps:

  1. A web token is returned when a user logs in successfully using their credentials (like email/password).
  2. Now, whenever the user wants to access a route or a resource on a web app that's protected, the user agent sends this token in the authorization header such as: Authorization: Bearer token

As you can see, it uses the Bearer schema, which is a cryptic string usually generated by the server in response to a login request.

  1. Next, the server's routes will check whether the provided access toke is valid in the Authorization header.
  2. If it's valid, the user is allowed to access the requested protected routes.

Here's a diagram that shows how the access token is obtained from the authorization server in order to access protected routes:

A diagram showing how the access token is obtained from the authorization server in order to access protected routes
  1. The client requests for authorization to the authentication server.
  2. After granting the authorization, the auth server returns an access token to the application.
  3. The application uses the token to access a protected route via some API.

Now that you know all about what access tokes are, where they're used, and how they work in a web app, let's try to take a look at using one of the authentication providers, i.e., Authgear.

How to Implement Authentication In Your Web App with Authgear?

We saw many ways to authenticate the user using different methods and how they work. Now let's take a practical approach toward authentication. We will be using Authgear here, so we will tell you all you need to know if you're unfamiliar with it. As for the web, we will be using the React.js library. Let's begin!

What is Authgear?

Authgear is an Customer Identity and Access Management (CIAM) solution for web and mobile apps built on top of the OpenID Connect (OIDC) standard, making it very easy to integrate with your new and existing applications.

It supports integrations with popular third-party service providers like Google, Apple, and Azure Active Directory (AD). Along with this, it also supports authentication via WhatsApp, email address and phone number via the One-Time Password (OTP) method.

Here are some of the features Authgear provides you by default:

1. Signup page: you don't need to create a custom signup page now, as you can use Authgear's prebuilt signup and login pages with best practices for signup conversions. You can even customize the look to align it with your brand visual identity.

A screenshot of Authgear's UI Setting feature that allows developers to customize the look of their signup/login page.

2. Multiple security features: you can easily implement social logins, Two-Factor Authentication (2FA), biometrics, and more features available to use to provide a smooth and secure user experience.

3. Password policies: you can have your customizable password policies to fulfill your corporate security requirements.

4. Sessions alert and revoke: you can easily ensure your user's security by listing their sessions and terminating any unknown sessions easily.

5. User profile & setting: This feature allows your users to have more control over their account information and activity. They can edit information, such as name, primary address, username, etc., of their profiles, manage their 2FAs, and terminate suspiscious sessions.

A screenshot of Authgear's User Profile & Setting feature, allowing users to manage their account information and activities.

6. Admin portals: your admin portal shows you everything you need to know about configuring the different authentication methods, adding security measures, or creating/revoking users with a few clicks.

What is React.js?

For integrating Authgear's web SDK, we will create our web application using the React.js library for JavaScript.

React.js (or React) is a declarative and component-based JavaScript library for building user interfaces for Single Page Applications (SPAs).

Setup Authgear for React

We will be using Authgear's web SDK in our React app. For this, first, we need to do a bit of setup.

Step 1: Signup for the Authgear Portal account

Visit https://portal.authgearapps.com/ and create a new account (or login into an existing one).

After you've created your Authgear account, you will be prompted to create a new project.

Step 2: Create and configure your project

You should see the following right now:

Create project dialog box

https://paper-attachments.dropbox.com/s_1D4860C51E02F9464386BCCE7C0402ACBCB39807BF815F98C7DC6EB33F4AF611_1657823844516_Create+project.png

You can name it anything you like, but you won't be able to change it later. This is your Authgear endpoint so choose wisely. Here, we call it ‘reactappdemo’.

Now we configure the project in the next three steps. Here, we choose the following settings:

  • Email and password
  • Users can enable 2FA optionally
  • TOTP Devices/Apps

After you choose your required settings, you will be greeted with the following:

Project creation finished interface

https://paper-attachments.dropbox.com/s_1D4860C51E02F9464386BCCE7C0402ACBCB39807BF815F98C7DC6EB33F4AF611_1657823875238_Project+setup+done.png

Now, you can click on “Continue to Portal for further Customisation”.

Step 3: Create an application

After creating the project, we will create an application. Make sure you're on your project, and then:

  1. Go to the ‘Applications’ option in the sidebar.
  2. Click 'Add Application' and input the name you want to give:

Create application interface in the Portal

https://paper-attachments.dropbox.com/s_1D4860C51E02F9464386BCCE7C0402ACBCB39807BF815F98C7DC6EB33F4AF611_1657823969390_Create+application.png

As you can see here, we also give it an “Authorized Redirect URI.” Users will be redirected to this path after they get authenticated. Typically, when we are in the development phase, we can give it http://localhost:4000/auth-redirect as URI for local development.

  1. Click the 'Save' button in the top toolbar, and you will be greeted with a popup containing the 'Client ID' copy it to your clipboard or save it somewhere.

Step 4: Configure the application

While on your app's ‘Edit Application’ section, check the ‘Issue JWT as access token’ checkbox under the ‘Token Settings’ section. This enables to use JWT as an access token and allows easier access token decoding. But if you will forward incoming requests to Authgear Resolver Endpoint for authentication, leave this unchecked.

Step 5: Add your website to allowed origins

We need our website origin to communicate with Authgear. For this:

  1. Go to the ‘Applications' > ‘Allowed Origins' section.
  2. Add your website origin URL here. If your app is already deployed, then it should be like yourdomain.com; else, use localhost:4000 for local development.
  3. Click ‘Save’.

You should have this by now:

https://paper-attachments.dropbox.com/s_1D4860C51E02F9464386BCCE7C0402ACBCB39807BF815F98C7DC6EB33F4AF611_1657823993934_Allowed+origins.png

With this, we are all ready to start some coding!

Scaffold a React app

Open up your Terminal and run the following command to create a React app:


npx create-react-app authgear-demo

We use the Create React App (CRA) tooling to scaffold an app quickly. Read more about this tool here.

Install Authgear's Web SDK

Authgear's web SDK is available as an NPM package. You can install it either via NPM or Yarn:


npm install --save --save-exact @authgear/web
// OR
yarn add @authgear/web --exact

Now open up the newly created authgear-demo app in your favorite code editor.

Initialize the Authgear SDK

Head over to the App.js root file. Here, we need to do a bit of cleanup. We need to add the SDK initialization code correctly before use; for that, we add the following code:


authgear
	.configure({
		endpoint: 'https://yourapp.authgearapps.com',
			clientID: 'YOUR_CLIENT_ID',
			sessionType: 'refresh_token',
	 })
.then(
	() => {
		console.log('Succesfully configured!');
	},
	(err) => {
		console.log('Failed to configure', err);
	}
);
	

Don't forget to import authgearin the first place:

import authgear from '@authgear/web';

In the above code, we call the configure method every time our page loads up. The configure method takes in an endpoint, a default domain you can see in your Authgear admin portal. It is something like: https://yourapp.authgearapps.com. We also give it the clientID of our application and the sessionType, which can be "refresh_token" or if you use cookie-based authentication, it can be "cookie".

Next, we handle our configuration further using the .then() method, where we can add code for successful or failed configurations.

Log in to your application

After successfully configuring the web SDK, we can go ahead with making the user log in to our app.

Step 1: Replace the default JSX code with the following:

    
    function App() {
        return (
            <div className='App'>
                <button style={{ marginTop: '10rem' }} onClick={handleOnClick}>
                    Signup / Login
                </button>
            </div>
            );
    }
    export default App;
    	

In our JSX, we have a simple button with some margin style and an onClick handler function handleOnClick. Next, we write our custom function as:


function handleOnClick() {
authgear(
	.startAuthorization({
		redirectURI: 'https://localhost:3000/auth-redirect',
		prompt: 'login',
	})
.then(
	() = > {
		console.log('Auth Started')
	},
		(err) => {
			console.log('Failed to authorize',, err);
		}      
	);
}
	

Here, we make our start authorization call so that we can redirect our user to the login/signup page.

The startAuthorization method takes in a redirectURI which we already configured in our portal. This is the path on which users will be redirected after they are authorized with the credentials. With login, you can optionally set the prompt so that the user always reaches the login page.

Step 2: Next, we need to handle the auth result in the redirectURI.

After authentication, the user will be redirected to the redirectURI with a code parameter in the URL query. Let's add the following code to make a finish authorization call:


authgear.finishAuthorization().then(
	(userInfo) => {
		// authorized successfully
		console.log('Authorized successfully');
	},
	(err) => {
		// failed to finish authorization
    console.log('Failed to finish authorization', err);
  }
);
  

We call the finishAuthorization method on authgear, which returns a userInfo. Upon its successful implementation, you should navigate the user to another path in your application. Else, you can print out the error. With that implemented, you have now successfully logged the user in! Head over to the Authgear portal and click 'User Management' in the sidebar to check the recently logged-in user. From here, you can disable, delete and check user details.

Contact us to learn more about how Authgear can help you improve user experience, increase conversion rate, and ensure security for your apps.

You may also refer to our Authgear Docs for more instructions.