Skip to main content

Securing Angular Apps with Keycloak

· One min read
Phase Two
Hosted Keycloak and Keycloak Support

In this article we'll be using Keycloak to quickly secure a Angular application with user management and single sign on (SSO) using the open source IAMs Keycloak for Authentication and Authorization. We will demonstrate the integration by securing a page for logged-in users. This quickly provides a jump-off point to more complex integrations.

info

If you just want to skip to the code, visit the Phase Two Angular example.

If you want to see a live example, visit the Phase Two Angular example.

Setting up a Keycloak Instance

Instructions
tip

If you already have a functioning Keycloak instance, you can skip to the next section.

Rather than trying to set up a "from scratch" instance of Keycloak, we're going to short-circuit that process by leveraging a free Phase Two Starter instance. The Starter provides a free hosted instance of Phase Two's enhanced Keycloak ready for light production use cases.

  • Visit the sign-up page.

  • Enter an email, use a Github account, or use an existing Google account to register.

    Phase Two Register

  • Follow the register steps. This will include a sign-in link being sent to your email. Use that for password-less login.

    Phase Two Email Magic Link Register

  • After creating an account, a realm is automatically created for you with all of the Phase Two enhancements. You need to create a Deployment in the Shared Phase Two infrastructure in order to gain access to the realm. Without a deployment created, the Create Shared Deployment modal will automatically pop up.

  • Create a Shared Deployment by providing a region (pick something close to your existing infrastructure), a name for the deployment, and selecting the default organization that was created for you upon account creation. Hit "Confirm" when ready. Standby while our robots get to work generating your deployment. This can take a few seconds.

    Phase Two Create Shared Deployment

  • After the deployment is created and active, you can access the Keycloak Admin console by clicking "Open Console" for that deployment. Open it now to see the console.

    Phase Two Open Console Keycloak Admin UI

At this point, move on to the next step in the tutorial. We'll be coming back to the Admin Console when its time to start connecting our App to the Keycloak instance.

Setting up an OIDC Client

Instructions

We need to create a OpenID Connect Client in Keycloak for the app to communicate with. Keycloak's docs provide steps for how to create an OIDC client and all the various configurations that can be introduced. Follow the steps below to create a client and get the right information necessary for app configuration.

  1. Open the Admin UI by clicking Open Console in the Phase Two Dashboard.

  2. Click Clients in the menu.

  3. Click Create client.

  4. Leave Client type set to OpenID Connect.

  5. Enter a Client ID. This ID is an alphanumeric string that is used in OIDC requests and in the Keycloak database to identify the client.

  6. Supply a Name for the client.

  7. Click Next.

    Keycloak OIDC Create Client General Settings

  8. Under the Capability Config section, leave the defaults as selected. This can be configured further later.

    • Client authentication to Off.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config

  10. Under Login settings we need to add a redirect URI and Web origin in order. Assuming you are using the example applicaiton:

    Valid redirect URI (allows redirect back to application)

    http://localhost:3000/*

    Web origins (allows for Token auth call)

    http://localhost:3000
    URI and Origin Details

    The choice of localhost is arbitrary. If you are using an example application running locally, this will apply. If you are using an app that you actually have deployed somewhere, then you will need to substitute the appropriate URI for that.

  11. Click Save

    Keycloak OIDC Create Login Settings

OIDC Config

We will need values to configure our application. To get these values follow the instructions below.

  1. Click Clients in the menu.

  2. Find the Client you just created and click on it. In the top right click the Action dropdown and select Download adapter config.

  3. Select Keycloak OIDC JSON in the format option. The details section will populate with the details we will need.

    • Note the realm, auth-server-url, and resource values.

    Keycloak OIDC Create Client Adapter Config

Adding a Non-Admin User

Instructions
tip

It is bad practice to use your Admin user to sign in to an Application.

Since we do not want to use our Admin user for signing into the app we will build, we need to add a another non-admin user.

  1. Open the Admin UI by clicking Open Console in the Phase Two Dashboard.
  2. Click Users in the menu.
  3. Click Add user.
  4. Fill out the information for Email, First name, and Last name. Click Create.
  5. We will now set the password for this user manually. Click Credentials (tab) and click Set Password. Provide a password for this user. For our use case, as a tutorial, you can leave "Temporary" set to "Off".
  6. Click Save and confirm the password by clicking Save password

Setting up a Angular Project

info

We will use the Phase Two Angular example code here, but the logic could easily be applied to any existing application.

  1. Clone the Phase Two example repo.
  2. Open the Angular folder within /frameworks/angular.
  3. Run npm install and then npm run start. This example leverages angular-oauth2-oidc OIDC methods.
  4. We'll review where we configure out Keycloak instance. Open the src/app/auth.config.ts file. We will be updating a few values from the prior section where we set up our OIDC client. Taking the values from the OIDC Client Config section, set those values in the code.
export const authCodeFlowConfig: AuthConfig = {
// Update this with the url and realm of your hosted Keycloak instance
issuer: "https://app.phasetwo.io/auth/realms/p2examples",
redirectUri: window.location.origin + "/index.html",
// Update this to the Client ID you created in the OIDC Client section
clientId: "angular",
responseType: "code",
scope: "openid profile email offline_access",
showDebugInformation: true,
};

Those are used to configure the oauthService in the src/app/user/user.component.ts file. In the constructor of the component, this is passed in.

// ...
constructor(private oauthService: OAuthService) {
this.oauthService.configure(authCodeFlowConfig);

// required to initialize the client
this.oauthService.loadDiscoveryDocumentAndTryLogin();
this.oauthService.setupAutomaticSilentRefresh();

this.oauthService.events
.pipe(filter((e) => e.type === 'token_received'))
.subscribe((_) => this.oauthService.loadUserProfile());
}
  1. The UserActivation.component.ts file contains additional methods that will assist with the interaction of the html template.

For handling login and logout, the following methods are used:

  signIn() {
return this.oauthService.initLoginFlow();
}

signOut() {
return this.oauthService.logOut();
}

while we also define additional helper methods to get user information (username, email, etc) along with raw Token values. A couple are provided below as an example.

get userName(): string {
const claims = this.oauthService.getIdentityClaims();
if (!claims) return '';
return claims['given_name'];
}

get idToken(): string {
const token = this.oauthService.getIdToken();
if (token) {
return this.decodeAndStringifyToken(token);
}
return '';
}
  1. Switching to the html template for the user component, src/app/user/user.component.html, we can see how the login and logout buttons are rendered. The buttons are conditionally rendered based on the user's authentication status based on the presence of the idToken.
<div *ngIf="idToken">
<!-- show user data -->
<!-- show logout button -->
</div>
<div *ngIf="!idToken">
<!-- show login button -->
</div>

The logic using the authenticator to conditionally determine the Authenticated state, can be used to secure routes, components, and more.

  1. Open localhost:4200. You will see the Phase Two example landing page. You current state should be Not authenticated. Click Log In. This will redirect you to your login page.
info

Use the non-admin user created in the previous section to sign in.

  1. Enter the credentials of the non-admin user you created. Click Submit. You will then be redirected to the application. The Phase Two example landing page now loads your Authenticated state, displaying your user's email and name.
  2. Neat! If you clear the browser state for that tab, then you will have to be redirected away to sign-in again.

Learning more

Phase Two's enhanced Keycloak provides many ways to quickly control and tweak the log in and user management experience. Our blog has many use cases from customizing login pages, setting up magic links (passwordless sign in), and Organization workflows.