4008063323.net

Enhancing Angular 15 Security with Code Flow PKCE and Duende IdentityServer

Written on

Introduction

To facilitate external logins in an Angular application, you can utilize third-party authentication services like Google, Facebook, Twitter, or Duende IdentityServer. These services offer APIs that help authenticate users and access their data.

In this post, we will delve into the architecture and procedures for implementing login functionality in an online demo identity server from Duende for _Angular v15_. This guide comprises the following sections:

  1. Architecture Overview: A discussion on the security architecture and custom libraries that support authentication in the Angular application.
  2. Sample Angular Application: Instructions for downloading and executing the sample Angular application on localhost to log in to the online demo IdentityServer.
  3. Angular and IdentityServer Communication: Utilizing the Chrome developer console to analyze the traffic and storage of the JSON Web Token (JWT).
  4. Source Code for Authentication Implementation: Examination of the source code and configurations in the sample Angular application for connecting to IdentityServer.

Part 1: Architecture Overview

In general, software developers should prioritize creating core functionalities and features of an application over implementing security protocols. While it’s crucial for developers to understand security best practices and mitigate common vulnerabilities like SQL injection and cross-site scripting, the more specialized security tasks are best left to professionals in the field.

Nevertheless, developers should possess a foundational understanding of security concepts and remain aware of potential risks while building applications. Before we delve deeper into the architecture, let's briefly overview Angular and Duende IdentityServer.

What is Angular?

Angular is a JavaScript-based framework for front-end web development, maintained by Google. It aims to streamline the process for developers to create single-page applications (SPAs) that are fast, responsive, and easy to maintain.

What is Duende IdentityServer?

Duende IdentityServer is an open-source framework for building identity and access management systems. Written in .NET, it is designed for ease of use and flexibility, enabling developers to swiftly construct authentication and authorization systems for their applications. IdentityServer secures applications and APIs through various authentication methods, including OIDC, SAML, and WS-Federation, often serving enterprise scenarios where a central identity provider manages access across multiple applications and services.

> Are there libraries available that simplify the login process for Angular developers to access Duende IdentityServer?

Yes! The NPM package _angular-oauth2-oidc_ offers support for OAuth 2 and OpenID Connect (OIDC) authentication within Angular. OAuth 2 is an open standard that permits users to grant third-party applications access to their resources without needing to share their credentials. OIDC builds upon OAuth 2, allowing developers to authenticate users and retrieve their identity data, such as name and email.

The _angular-oauth2-oidc_ library simplifies the implementation of OAuth 2 and OIDC in Angular applications. It provides several Angular services, components, and directives to manage the authentication process, including access token management, refresh tokens, and user profile information retrieval. The library is fully compliant with OAuth 2 and OIDC standards, ensuring compatibility with any compliant identity provider, such as IdentityServer, Okta, or Auth0.

Part 2: Tryout the Sample Angular Application

The sample application is pre-configured to log in to the Duende IdentityServer demo server at https://demo.duendesoftware.com. You will be redirected to the demo server for login. Follow these steps to download and run the sample application locally:

  1. Clone the example app from https://github.com/workcontrolgit/AngularOIDCExample
  2. Open the app in Visual Studio Code.
  3. Run npm install in the terminal.
  4. Execute npm start in the terminal.

For detailed step-by-step instructions on cloning a repository, refer to "How to git clone an Angular app on GitHub and run it on localhost."

Once the application is running, you can visit http://localhost:4200 in your web browser to see the application in action.

Click the user icon at the top right to log in, as illustrated in the next figure.

You will be redirected to the https://demo.duendesoftware.com site to log in with either a local or external account. The details for local login will be displayed above the Login button.

After logging in, IdentityServer will redirect you back to the Angular application. For instance, if you log in with the credentials (bob/bob), your name will appear when you click the user icon. To log out, click the Logout link below your name.

Selecting the Logout link will redirect you to Duende IdentityServer for logoff. Note that there will be an option to return to the Angular application.

For demonstration purposes, the About page is protected by an Auth Guard, accessible only to authenticated users. If an unauthenticated user attempts to access the About page, a toaster message saying Access denied will appear.

Part 3: Exploring Angular Communication with IdentityServer

The developer console in Google Chrome is an invaluable tool for web developers, allowing them to inspect and debug web pages. It offers features to analyze and fix code issues, such as viewing console messages, errors, and monitoring network requests.

Authentication Flow

Let's examine the Network tab to observe the interaction between Angular and Duende IdentityServer. Figure 7 illustrates a screenshot of network traffic immediately after login. The NPM package _angular-oauth2-oidc_ manages most of the login processes. Below are the IdentityServer API endpoints accessed by the Angular application:

  1. openid-configuration endpoint: This metadata document provides details about an OIDC provider's configuration, including URLs for various OIDC endpoints, available authentication methods, and supported claims. This metadata document is typically located at the well-known URL /.well-known/openid-configuration.
  2. token endpoint: Defined by the OpenID Connect specification, this endpoint is used to exchange authorization codes, refresh tokens, and client credentials for access tokens. In the context of an OIDC identity server, it allows clients to request access tokens by including parameters that identify the client and resource. If the request is valid, the identity server issues an access token.
  3. userinfo: This endpoint provides information about the authenticated user, including claims like their name, email, and other profile information. Clients can request user information by sending an access token obtained from the token endpoint. The identity server validates the access token and returns the requested claims if valid.

To inspect the JWT id and access token, navigate to the Application tab in the Developer Console and look for Local Storage. Click on id_token_claims_obj to view the claims.

Automatic JWT Token Attachment in Header

The sample application makes a WebAPI call to https://api.chucknorris.io to fetch a quote for display on the homepage. The _angular-oauth2-oidc_ library automatically includes the access token in the Authorization header for logged-in users.

JWT Token Silent Refresh

JWT refresh tokens are utilized to obtain new access tokens when the original ones expire, allowing continued authenticated requests without requiring users to re-enter their credentials.

The term "silent" in "JWT silent refresh" indicates that this process can occur without user intervention. A refresh token, which is a long-lived token stored on the client, is used to obtain a new access token without prompting the user for their credentials again.

To perform a JWT silent refresh, the client sends the refresh token to the authorization server, which verifies it. If valid, a new JWT access token is issued. The client can then utilize this access token for authenticated resource requests.

Source Code

The complete sample application (Angular v15, Bootstrap v5) is available for download on GitHub. The project is organized to facilitate easy integration into your own projects.

https://github.com/workcontrolgit/AngularOIDCExample

Summary

In summary, the _angular-oauth2-oidc_ library is an excellent resource for Angular developers needing to implement OAuth 2 and OIDC authentication in their applications. It simplifies the process and saves time by providing a collection of pre-built Angular components and services for common authentication tasks.

Congratulations! You have successfully learned about Angular _authentication_ through the implementation of external login with IdentityServer. What’s next? I challenge you to extend this knowledge into the _authorization_ domain. Check out my blog _Angular Guard for Role-Based Access Control (RBAC) Driven by JWT_.

> Thank you for reading! I hope you found this article helpful. For more content, please follow me and consider becoming a member on Medium. Your support encourages me to create more valuable articles for you. Have a wonderful day ahead! — Fuji Nguyen

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Exploring the Nature of Ultimate Reality and Its Implications

An in-depth discussion on the concept of ultimate reality, its scientific implications, and the intersection of faith and empirical evidence.

Exploring JetBrains Fleet: The Future of IDEs Unveiled

A deep dive into JetBrains' Fleet IDE, showcasing its features and potential for developers.

Understanding the Risks of Public Restrooms During COVID-19

Learn about the dangers of virus transmission in public restrooms and the importance of wearing masks to protect yourself and others.

Unlocking the Potential of Qwen1.5 LLMs: Inference and Quantization

Explore the capabilities of Qwen1.5 LLMs, their performance, and how to effectively utilize them on consumer hardware.

Rethinking Our Thought Processes in a Shifting Landscape

Exploring the need for independent thought in an increasingly controlled society.

Essential Insights Gained from Architecting an Enterprise Application

Discover key lessons learned from architecting an enterprise application, focusing on frontend architecture and best practices.

Find Someone Who Brings Joy Even in Tough Times

Discover the importance of being with someone who makes you smile, even during challenging moments.

Understanding the Misconceptions of Calories: A Deep Dive

Explore the truth about calories, their calculation, and why they deserve better recognition in our dietary choices.