From Login to Lockdown: Building Secure Authenticated Applications
Master the art of building secure authenticated applications. Learn about authentication methods, access tokens, and implement robust security with Authgear. Your comprehensive guide to safeguarding user data.
min. read
Last updated:
December 13, 2024
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 is an Authenticated Application?
An authenticated application is a software application that verifies a user's identity before granting access to its features and data. This essential security measure ensures that only authorized individuals can interact with the application.
Authentication involves confirming that a user is who they claim to be. This is typically achieved by requiring users to provide credentials such as usernames, passwords, or biometric data. Once verified, the application issues a digital token or session cookie, allowing the user to access protected resources.
Essentially, an authenticated application acts as a gatekeeper, safeguarding sensitive information and preventing unauthorized access.
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:
Cookie-Based Authentication
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:
As you can see here, the client browser sends the POSTrequest 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:
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 Connect (OIDC)
Building upon the OAuth 2.0 protocol, OpenID Connect (OIDC) simplifies user authentication by providing an authorization layer on top of it. This layer enables applications to verify user identities and obtain essential user information beyond just basic authentication. OIDC offers several advantages, including:
Single Sign-On (SSO): Users can log in to your application using their existing credentials from a trusted identity provider (IdP) like Google or Facebook, eliminating the need for separate login credentials for your application. This streamlines the login process and improves user experience.
Reduced Security Risk: By leveraging established IdPs for authentication, OIDC reduces the burden of managing user credentials on your application server. This minimizes the risk of data breaches and unauthorized access.
Rich User Information: OIDC allows applications to request and receive a broader scope of user information from the IdP beyond just usernames. This information can include profile details, email addresses, and preferences, potentially enriching the user experience within your application.
Security Assertion Markup Language (SAML)
Security Assertion Markup Language (SAML) is an XML-based standard for exchanging authentication and authorization data between online systems. It functions as a single sign-on (SSO) and federated identity management solution, specifically designed for enterprise environments. In an SSO scenario, a user logs in once to a central identity provider (IdP) and can then access multiple secure applications without needing to re-enter their credentials for each application. SAML relies on XML assertions to securely communicate authentication and authorization data between the IdP, the service provider (SP) requesting access (i.e., your web application), and potentially other trusted parties. This enables users to seamlessly move between different applications within a corporate network or cloud environment without encountering separate login prompts.
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:
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:
Here's how these tokens work in websites and web apps:
A web token is returned when a user logs in successfully using their credentials (like email/password).
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.
Next, the server's routes will check whether the provided access toke is valid in the Authorization header.
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:
The client requests for authorization to the authentication server.
After granting the authorization, the auth server returns an access token to the application.
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.
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.
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.
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
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
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:
Go to the ‘Applications’ option in the sidebar.
Click 'Add Application' and input the name you want to give:
Create application interface in the Portal
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.
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:
Go to the ‘Applications' > ‘Allowed Origins' section.
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.
Click ‘Save’.
You should have this by now:
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:
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:
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.authgear-apps.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:
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:
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. Or join our Discord server to learn more about web application authentication
Authgear understands the importance of data privacy, especially in today's digital landscape. In line with our Privacy Policy, we take your privacy seriously and are committed to being transparent about how we collect your information. By clicking "Accept," you consent to the use of all cookies on our site. However, you have the right to choose which types of cookies you allow. Simply click on "Manage Settings" to customize your preferences.
Privacy is important to us, so you have the option of disabling certain types of storage that may not be necessary for the basic functioning of the website. Blocking categories may impact your experience on the website.