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.
Phase Two is a Keycloak as a Service provider enabling SaaS builders to accelerate time-to-market with powerful enterprise features like SSO, identity, and user management features. Phase Two enhances Keycloak through a variety of open-source extentions for modern SaaS use cases. Phase Two supports both hosted and on-premise deployment options.
What is Keycloak?
Keycloak has been a leader in the Identity and Access Management world since its launch almost 8 years ago. It is an open-source offering under the stewardship of Red Hat
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.
TOC
Setting up a Keycloak Instance
TIP
If you already have a functioning Keycloak instance, you can skip to the next section.
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.Keycloak Setup Details
Rather than trying to set up a "from scratch" instance of Keycloak, we're going to short-circuit that process by leveraging a Phase Two free Keycloak starter instance. The Starter provides a free hosted instance of Phase Two's enhanced Keycloak ready for light production use cases.
Setting up an OIDC Client
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. Under Login settings we need to add a redirect URI and Web origin in order. Assuming you are using the example application: Valid redirect URI (allows redirect back to application)Details
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.
http://localhost:3000/*
_Web origins_ (allows for Token auth call)
```
http://localhost:3000
OIDC Config
We will need values to configure our application. To get these values follow the instructions below.Details
Adding a Non-Admin User
INFO
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 another non-admin user.
Details
Angular
INFO
We will use the Phase Two Angular example code here, but the logic could easily be applied to any existing application.
- Clone the Phase Two example repo.
- Open the Angular folder within
/frameworks/angular
. - Run
npm install
and thennpm run start
. This example leverages angular-oauth2-oidc OIDC methods. - 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. ```tsx
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.
```tsx
// ...
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());
}
- 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: ```tsx
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.
```tsx
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 '';
}
- 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 theidToken
. ```html
The logic using the authenticator to conditionally determine the Authenticated state, can be used to secure routes, components, and more.
1. Open [localhost:4200](http://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.
12. 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](https://phasetwo.io/blog) has many use cases from [customizing login pages](https://phasetwo.io/blog/customizing-login-pages), setting up [magic links](https://phasetwo.io/blog/set-up-magic-links) (password-less sign in), and [Organization](https://phasetwo.io/product/organizations) workflows.
Top comments (0)