Skip to main content

9 posts tagged with "authentication"

View All Tags

· 5 min read

Exploring Keycloak as an Alternative to Auth0 for Authentication Solutions

When it comes to implementing authentication and authorization in web applications, Auth0 and Keycloak are two prominent solutions that offer robust security features. While Auth0 is a popular choice for many developers due to its comprehensive, cloud-based platform, Keycloak presents a compelling alternative, especially in terms of cost and flexibility. This blog post will delve into how Keycloak stacks up against Auth0, focusing on cost of ownership, maintenance, and functionality.

Cost of Ownership

There are many factors to think about with a total cost-of-ownership. We've written extensively about choosing an Open-Source IAM over a managed service.

Auth0: Auth0 operates on a subscription model, which can be quite enticing for startups or small projects with minimal authentication needs. It offers a free tier limited by the number of authentications per month, active users, MFA setups, and more. As needs quickly increase for a business to setup a modest number of IDP connections, include minimal additional "users" (which could be people or devices), extract logs, customize deployments, and more, those bills can quickly spiral into $100K+. For SMB's to Enterprise, dedicating that amount of resources to your Auth solution can be untenable.

Keycloak: Keycloak, on the other hand, is an open-source solution developed by Red Hat. It is free to use, regardless of the number of users or the scale of the project. This makes Keycloak particularly attractive for businesses looking to cut costs or those who prefer not to be tied to vendor-specific pricing structures. The primary cost associated with Keycloak comes from the need to self-host and manage the software, which includes server costs and potential overhead for setup and maintenance. This can mean the ongoing cost is fixed since its not driven by features or users.

Winner

Keycloak

Leveraging Phase Two's managed hosting provides a more capable free tier to test out and integrate Authorization and Authentication into an application(s). When that application's needs grow, Keycloak quickly becomes a far more cost-effective choice.

Maintenance

Auth0: One of the main advantages of Auth0 is that being a managed service, it requires minimal maintenance from the user's side. The Auth0 team handles updates, security patches, and infrastructure, ensuring that the system is kept up-to-date.

Keycloak: Conversely, Keycloak requires more attention since it's self-hosted. Organizations must allocate resources for installing, configuring, and updating the software, as well as managing the underlying infrastructure. This can be a drawback for teams without the necessary technical expertise or resources. However, it also offers greater control over the deployment and security standards, which can be a significant advantage for certain regulatory environments.

Winner

Auth0.

As a fully managed service, Auth0 abstracts away this work.

Functionality and Flexibility

Auth0: Auth0 offers a wide range of authentication features out-of-the-box, including social logins, enterprise federation, database connections, and more. It supports a variety of standards like OAuth2, OpenID Connect, and SAML, making it highly versatile for modern web applications. The platform also provides robust analytics and real-time monitoring tools that can be crucial for understanding user behavior and mitigating potential security threats.

Keycloak: Keycloak matches Auth0 in terms of functionality, supporting similar authentication protocols and user federation. It also offers customizable user interfaces for login, registration, and account management, which can be tailored to match the specific needs of a business. Being open-source, Keycloak allows developers to modify the codebase and integrate with other systems more freely than Auth0, offering a higher degree of customization at the cost of additional developer effort.

Winner

Keycloak

Auth0 and Keycloak offer much of the same functionality for Authenication and Authorization, however Keycloak is extremely flexible to extend and configure. It's a system that can adjust and grow with an application.

Integrating Keycloak with External Systems like Auth0

For organizations looking to transition from Auth0 to Keycloak or integrate Keycloak with systems that are already using Auth0, Keycloak's flexibility offers significant advantages. Keycloak can be configured to act as a broker that sits between Auth0 and your applications. This setup allows organizations to leverage the strengths of both platforms. For example, an organization can use Auth0 for external user management due to its robust third-party integrations while using Keycloak to handle more sensitive internal authentication needs.

The identity brokering capability of Keycloak enables it to delegate authentication to external Identity Providers (IdPs), such as Auth0. This means that Keycloak can manage internal permissions and roles, provide additional security checks, and maintain a user-friendly, consistent login experience across different systems. The ability to integrate seamlessly with services like Auth0 simplifies the migration process for companies transitioning from one authentication system to another and provides a layer of flexibility for new authentication strategies without disrupting user access or security.

Which One Is Best for Me?

Choosing between Auth0 and Keycloak largely depends on your organization’s specific needs and capabilities. Auth0 is an excellent choice for those who need a fully managed solution with costs linked to user numbers and features. However, for organizations that prioritize cost savings and predictability, have the capability to manage their infrastructure, or require extensive customization, Keycloak emerges as a powerful, budget-friendly alternative.

Both platforms offer extensive documentation and community support, which can help mitigate some of the challenges associated with implementation and maintenance.

Ultimately, we at Phase Two believe marrying the two together is the strongest match. We offer robust hosting options that fit well for multiple business sizes. Coupling the capabilities of Keycloak and the advantages of a managed service translates directly to implementation and cost control. Leveraging Keycloak means that ongoing costs are relatively fixed, since concerns about user growth or feature needs don't have to factor into every decision.

· 4 min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 SvelteKit example. We also have a plain React 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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 SvelteKit Project

info

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

  1. Clone the Phase Two example repo.
  2. Open the SvelteKit folder within /frameworks/sveltekit.
  3. Run npm install and then npm run dev. This example leverages @auth/sveltekit to provide HOC support.
  4. The project makes use of the following SvelteKit items: hooks, components, layout, and @auth/sveltekit module. We'll review each in kind.
  5. We'll review where we configure out Keycloak instance. Open the src/auth.ts file. This is a server only 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. While it is recommended to use Environment variables for the secret, for the purpose of this tutorial, paste in the Client secret from the OIDC client creation section for the value of clientSecret.
// Use Environment Variables AUTH_SECRET in prod
const authjsSecret = "f18d48ce9bea32e44b5591b2c89185729d4559435f77ca76872a83a0850563a4";

const realm = "shared-deployment-001";

const kcConfig = {
// Use Environment Variables AUTH_KEYCLOAK_ISSUER in prod
issuer: `https://usw2.auth.ac/auth/realms/${realm}`,
// Paste "Client id" here. Use Environment Variables AUTH_KEYCLOAK_ID in prod
clientId: "reg-example-1",
// Paste "Client secret" here. Use Environment Variables AUTH_KEYCLOAK_ISSUER in prod
clientSecret: "CLIENT_SECRET",
};

Those are used to popluate the config for the provider Keycloak:

export const { handle, signIn, signOut } = SvelteKitAuth({
trustHost: true,
secret: authjsSecret,
providers: [Keycloak(kcConfig)],
});
  1. Next, let's review the hooks (src/hooks.server.ts) file. This imports the handle method by the src/auth.ts and re-exports it. This allows the hooks to act as a middleware and include the authentication status of the user in each request.
export { handle } from "./auth.js";
  1. To retrieve the authentication status of the user in server-side rendering on the index route, it's using the +layout.server.ts file. It retrieves the authentication status via the getSession function from SvelteKit Locals set by src/hook.server.ts.
import type { LayoutServerLoad } from "./$types.js";

export const load: LayoutServerLoad = async (event) => {
const session = await event.locals.getSession();
return {
session,
};
};
  1. The server-side authentication data is then accessed inside the +page.svelte, and then passed onto the user (src/components/user.svelte) component as follows:
<script lang="ts">
import User from "$components/user.svelte";
import type { LayoutServerData } from "./$types.js";

export let data: LayoutServerData;
</script>

// ... Rest of the index route ... //

<User
data={{
user: data?.session?.user,
status: Boolean(data?.session),
}}
/>

The props, user and status represent the user information object and whether the user is signed in, respectively.

  1. At this point our entire application will be able to access all information and methods needed to perform authentication. View src/components/user.svelte for exactly how the code is authenticating your user. The sections rendering the Log in and Log out buttons are conditional areas based on the authenticated context. The buttons invoke server-side APIs provided by @auth/sveltekit.

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

  1. Open localhost:3000. 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.

  2. 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.

  3. 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 (password-less sign in), and Organization workflows.

· 4 min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 Remix example. We also have a plain React 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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 Remix Project

info

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

  1. Clone the Phase Two example repo.
  2. Open the Remix folder within /frameworks/remix.
  3. Run npm install and then npm run dev -- --port 3000. This example leverages remix-auth and remix-keycloak to provide HOC support.
  4. Open the app/services/keycloak.server.ts file. This is a server only 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. While it is recommended to use Environment variables for the secret, for the purpose of this tutorial, paste in the Client secret from the OIDC client creation section for the value of clientSecret:
const kcConfig = {
useSSL: true,
domain: "usw2.auth.ac/auth",
realm: "shared-deployment-001",
clientID: "reg-example-1",
clientSecret: "CLIENT_SECRET", // Paste "Client secret" here. Use Environment variables in prod
callbackURL: "http://localhost:3000/auth/keycloak/callback",
};

Those are used to popluate the config for the KeycloakStrategy:

export default new KeycloakStrategy(kcConfig, ({ profile }) => profile);

The config is then used with the Authenticator instance in the app/services/auth.server.ts file. The authenticator instance uses the Session Storage to manage the state of authentication via a cookie.

import { Authenticator } from "remix-auth";
import keycloakServer from "./keycloak.server";
import { sessionStorage } from "~/services/session.server";

export const authenticator = new Authenticator(sessionStorage);

authenticator.use(keycloakServer);

At this point our entire application will be able to access all information and methods needed to perform authentication. View the session.server.ts file for additional information about how the SessionStorage is used. The SessionStorage stores the Keycloak token and is used to derive the authenticated state. View user.tsx for exactly how the code is authenticating your user. The sections rendering the Log in and Log out buttons are conditional areas based on the authenticated context. The buttons invoke server-side APIs provided by remix-auth.

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

  1. Open localhost:3000. 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.

  2. 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.

  3. 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 (password-less sign in), and Organization workflows.

· One min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 Vue 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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 Vue.js Project

info

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

This example uses Vue.js. We're going to leverage oidc-client-ts to integrate OIDC authentication with the Vue app. The oidc-client-ts package is a well-maintained and used library. It provides a lot of utilities for building out a fully production app.

  1. Clone the Phase Two example repo.

  2. Open the Vue folder within /frameworks/vue and open the /nuxt/oidc-client-ts folder.

  3. Run npm install and then npm run dev.

  4. We'll review where we configure out Keycloak instance. First open /auth.ts. In this file you will want to update it with the values for the Keycloak instance we set-up earlier in the tutorial. Update the clientSecret with the value. Use and environment variable here if you wish.

    export const keycloakConfig = {
    authorityUrl: "https://euc1.auth.ac",
    applicationUrl: "http://localhost:3000",
    realm: "shared-deployment-001",
    clientId: "reg-example-1",
    clientSecret: "CLIENT_SECRET",
    };

    After the config, you can see how the OIDC instance is started.

    const settings = {
    authority: `${keycloakConfig.authorityUrl}/auth/realms/${keycloakConfig.realm}`,
    client_id: keycloakConfig.clientId,
    client_secret: keycloakConfig.clientSecret,
    redirect_uri: `${window.location.origin}/auth`,
    silent_redirect_uri: `${window.location.origin}/silent-refresh`,
    post_logout_redirect_uri: `${window.location.origin}`,
    response_type: "code",
    userStore: new WebStorageStateStore(),
    loadUserInfo: true,
    };
    this.userManager = new UserManager(settings);
  5. With the Keycloak instance defined, we attach this to the app instance for Vue. Switch to /main.ts

    import Auth from "@/auth";
    // ...
    app.config.globalProperties.$auth = Auth;

    We pull in the Auth instance then expose it through the $auth variable.

  6. There are a few main pages in play here that we define to create paths the library can leverage. The /view/auth and /view/silent-refresh create paths at the same name. These are used to do the redirection during authentication. From within these we use the Auth instance to direct the user around within the app. For instance in /views/AuthView:

    export default {
    name: "AuthAuthenticated",
    async mounted() {
    try {
    await this.$auth.signinCallback();
    this.$router.push("/");
    } catch (e) {
    console.error(e);
    }
    },
    };

    The router.push naively sends someone to the home page. This could be updated to go to any number of places, including the page one started the login flow from if you were to store that information to be retrieved.

  7. Now that we have all the things setup, we can define the user component /components/User to easily pull information about the user's state and display the appropriate UI.

    export default {
    name: "UserComponent",
    data() {
    return {
    user: null,
    signIn: () => this.$auth.signinRedirect(),
    logout: () => this.$auth.signoutRedirect(),
    };
    },
    async created() {
    const user = await this.$auth.getUser();
    if (user) {
    this.user = user;
    }
    },
    };

    With this, the user object is now easily available. A simple v-if="user" allows the app to determine what UI to show.

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 (password-less sign in), and Organization workflows.

· 7 min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 Nuxt 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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 Nuxt Project

info

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

This example uses Nuxt3. There are a couple methods by which you can integrate Keycloak to your Nuxt application. We're going to explore two methods here, one uses keycloak-js and the other leverages oidc-client-ts. The keycloak-js library provides a simple, client-only method, but lacks some of the sophistication provided by the oidc-client library that is heavily supported and more widely used.

Using keycloak-js

info

For this example, we need to disable "Client Authentication" in the OIDC client that was setup earlier. This is available under Client > Settings > Capability config > Client authentication to OFF.

  1. Clone the Phase Two example repo.

  2. Open the Nuxt folder within /frameworks/nuxt and open the keycloak-js folder within /frameworks/nuxt/keycloak-js.

  3. Run npm install and then npm run dev. keycloak-js is a Javascript library that provides a fast way to secure an application.

  4. The project makes use of the following Nuxt items: components, composables, layouts, and plugins. We'll review each in kind.

  5. The main component that shows the User's authenticated state is in /components/User. In this component we call the useKeycloak composable, which let's us key into the keycloak-js functions that we've wrapped to make easily availble.

    const { keycloak, authState } = useKeycloak();

    function login() {
    keycloak.login();
    }

    function logout() {
    keycloak.logout();
    }

    Lower in the file the component leverages v-if checks to determine if the authState is authenticated or not. Depending on the state, a Log in or Log out button is available.

  6. Let's take a look at the setup for the composable next. Our composable is in /composables/keycloak-c. A composable is a function defined that can be called anywhere in the Nuxt application. It's a good way to abstract logic to be reused. In our case we use it to wrap a keycloak-js plugin (more on that in the next step) and help provided a state value for the authenticated state.

    export const useKeycloak = () => {
    const nuxtApp = useNuxtApp();
    const keycloak = nuxtApp.$keycloak as Keycloak;
    const authState = useState("authState", () => "unAuthenticated");

    keycloak.onAuthSuccess = () => (authState.value = "authenticated");
    keycloak.onAuthError = () => (authState.value = "error");

    return {
    keycloak,
    authState,
    };
    };
  7. In the plugin, /plugins/keycloak.client.ts we instantiate the keycloak-js library. We can then attach that instance to the NuxtApp instance. Substitute the correct values for your Keycloak instance that we created earlier in the tutorial.

    export default defineNuxtPlugin((nuxtApp) => {
    const initOptions: KeycloakConfig = {
    url: "https://euc1.auth.ac/auth/",
    realm: "shared-deployment-001",
    clientId: "reg-example-1",
    };

    const keycloak = new Keycloak(initOptions);

    nuxtApp.$keycloak = keycloak;

    keycloak.init({
    onLoad: "check-sso",
    });
    });
  8. The logic for checking the authenticated state can be used to expand in ways to secure your site in a number of ways.

Using oidc-client

The oidc-client-ts package is a well-maintained and used library. It provides a lot of utilities for building out a fully production app.

  1. Clone the Phase Two example repo.

  2. Open the Nuxt folder within /frameworks/nuxt and open the /nuxt/oidc-client-ts folder.

  3. Run npm install and then npm run dev.

  4. The structure of the project is similar to the keycloak-js version but with a the use of services, stores, and middleware.

  5. We'll review where we configure out Keycloak instance. First open /services/keycloak-config.ts. In this file you will want to update it with the values for the Keycloak instance we set-up earlier in the tutorial. Make sure you are using the one with Client Authentication enabled. Update the clientSecret with the value. Use and environment variable here if you wish.

    export const keycloakConfig = {
    authorityUrl: "https://euc1.auth.ac",
    applicationUrl: "http://localhost:3000",
    realm: "shared-deployment-001",
    clientId: "reg-example-1",
    clientSecret: "CLIENT_SECRET",
    };
  6. Switch over to the /services/auth-service now to see how the Oidc instance is started. The class pulls in values from the keycloakConfig to use in the constructor. The other functions are wrappers around methods provided by the oidc-client library. This allows us to key into things like signInRedirect and signoutRedirect.

    How the settings are integrated:

    const settings = {
    authority: `${keycloakConfig.authorityUrl}/auth/realms/${keycloakConfig.realm}`,
    client_id: keycloakConfig.clientId,
    client_secret: keycloakConfig.clientSecret,
    redirect_uri: `${window.location.origin}/auth`,
    silent_redirect_uri: `${window.location.origin}/silent-refresh`,
    post_logout_redirect_uri: `${window.location.origin}`,
    response_type: "code",
    userStore: new WebStorageStateStore(),
    loadUserInfo: true,
    };
    this.userManager = new UserManager(settings);

    Example function wrapper:

    public signInRedirect() {
    return this.userManager.signinRedirect();
    }
  7. With the AuthService defined, we can now expose that through a composable. Switch to the /composables/useServices file. The file is simple but provides a way for any component to hook into the service instance.

    import AuthService from "@/services/auth-service";
    import ApplicationService from "@/services/application-service";
    import { useAuth } from "@/stores/auth";

    export const useServices = () => {
    const authStore = useAuth();

    return {
    $auth: new AuthService(),
    $application: new ApplicationService(authStore.access_token),
    };
    };

    We pull in the AuthService then expose it through the $auth variable. The $application variable exposes the ApplicationService which is provided as an example of how you could secure API calls.

  8. We leverage the pinia library to make store User information to make it easily accessible. Open /stores/auth/index. From within this file, we can wrap the User object exposed by the oidc-client package. This can then be leveraged in the middleware function we want to define or to pull information quickly about the user.

  9. There are a few main pages in play here that we define to create paths the library can leverage. The /pages/auth, /pages/logout, /pages/silent-refresh create paths at the same name. These are used to do the redirection during authentication or log out. From within these we use the AuthService to direct the user around within the app. For instance in /auth:

    const authenticateOidc = async () => {
    try {
    await services.$auth.signInCallback();
    router.push("/");
    } catch (error) {
    console.error(error);
    }
    };

    await authenticateOidc();

    The router.push naively sends someone to the home page. This could be updated to go to any number of places, including the page one started the login flow from if you were to store that information to be retrieved.

  10. We have also created a middleware file in /middleware/auth.global to be used in a couple of ways. It checks if the user is authenticated and based on that knowledge, stores the user information in the store (if not there) or could be used to send someone to login. For our example, we created buttons to initiate that but there is a comment which shows how you could force a set of paths to require login.

    const authFlowRoutes = ["/auth", "/silent-refresh", "/logout"];

    export default defineNuxtRouteMiddleware(async (to, from) => {
    const authStore = useAuth();
    const services = useServices();
    const user = (await services.$auth.getUser()) as User;

    if (!user && !authFlowRoutes.includes(to.path)) {
    // use this to automatically force a sign in and redirect
    // services.$auth.signInRedirect();
    } else {
    authStore.setUpUserCredentials(user);
    }
    });
  11. Now that we have all the things setup, we can define the user component /components/User to easily pull information about the user's state and display the appropriate UI.

    const authStore = useAuth();
    const user = authStore.user;

    const signIn = () => services.$auth.signInRedirect();
    const signOut = () => services.$auth.logout();

    With this, the user object is now easily available. A simple v-if="user" allows the app to determine what UI to show.

  12. A bit more complicated of a setup, but more elegant in the handling of the logged in flow. The oidc-client allows for much better fine-tuning of the experience.

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 (password-less sign in), and Organization workflows.

· 6 min read

Django is a high-level, open-source web framework for building web applications using the Python programming language. It follows the Model-View-Controller (MVC) architectural pattern.

In this article we'll be using Keycloak to secure a Django Web application.

info

If you just want to skip to the code, visit the Phase Two Django example. We are also building Keycloak examples for other frameworks.

Setting up a Django Project

The following could be applied to an existing Django application, but we have chosen to use the excellent tutorial application built by Mozilla as our example. If you aren't yet familiar with Django, we encourage you to follow the tutorial there.

The completed code for that tutorial is available in their GitHub repository. We'll clone it to get started.

Quick Start

To get this project up and running locally on your computer:

  1. Set up the Python development environment. We recommend using a Python virtual environment.
  2. Assuming you have Python setup, run the following commands (if you're on Windows you may use py or py -3 instead of python to start Python):
    pip install -r requirements.txt
    python manage.py makemigrations
    python manage.py migrate
    python manage.py collectstatic
    python manage.py test # Run the standard tests. These should all pass.
    python manage.py createsuperuser # Create a superuser
    python manage.py runserver
  3. Open a browser to http://127.0.0.1:8000/admin/ to open the admin site
  4. Create a few test objects of each type.
  5. Open tab to http://127.0.0.1:8000 to see the main site, with your new objects.

Setting up a Keycloak Instance

Before customizing the Django app, we need to set up and configure our 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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

Install and configure the Django OIDC library

Now that we've installed and configured Keycloak, we need to setup Django to replace the native authentication method provided by the framework. The first task is to install a library that is compatible with Keycloak's OIDC implementation.

The mozilla-django-oidc library provides an easy way to integrate Keycloak (or any OpenID Connect-compliant identity provider) with your Django app. It abstracts many of the complexities of integrating authentication and authorization. Here's how you can set it up:

  1. Install the Package: Install the mozilla-django-oidc package using pip:

    pip install mozilla-django-oidc
  2. Configure Django Settings: Update your Django app's settings.py to include the necessary configurations for mozilla-django-oidc:

    INSTALLED_APPS = [
    # ...
    'django.contrib.auth',
    'mozilla_django_oidc', # Load after django.contrib.auth
    # ...
    ]

    AUTHENTICATION_BACKENDS = (
    'mozilla_django_oidc.auth.OIDCAuthenticationBackend',
    # ...
    )

    OIDC_RP_CLIENT_ID = 'your-client-id'
    OIDC_RP_CLIENT_SECRET = 'your-client-secret'
    OIDC_OP_AUTHORIZATION_ENDPOINT = 'https://keycloak-url/auth/realms/your-realm/protocol/openid-connect/auth'
    OIDC_OP_TOKEN_ENDPOINT = 'https://keycloak-url/auth/realms/your-realm/protocol/openid-connect/token'
    OIDC_OP_USER_ENDPOINT = 'https://keycloak-url/auth/realms/your-realm/protocol/openid-connect/userinfo'
    OIDC_OP_JWKS_ENDPOINT = 'https://keycloak-url/auth/realms/your-realm/protocol/openid-connect/certs'
    OIDC_RP_SIGN_ALGO = 'RS256'

    LOGIN_URL = 'oidc_authentication_init'
    LOGOUT_REDIRECT_URL = '/'
    LOGIN_REDIRECT_URL = '/'

    Replace your-client-id, your-client-secret, and the Keycloak URLs with your actual Keycloak configurations.

  3. Add URLs: Update your Django app's urls.py to include the authentication URLs provided by mozilla-django-oidc:

    urlpatterns += [
    path('oidc/', include('mozilla_django_oidc.urls')),
    ]

Using it in your app

Protect your views

Use Decorators for Access Control. You can now use the @oidc_protected decorator to protect views that require authentication and potentially specific roles:

from mozilla_django_oidc.decorators import oidc_protected

@oidc_protected
def protected_view(request):
# Your view logic

Accessing user information

You can access user information after authentication using the request.oidc_user attribute. For example:

def profile_view(request):
user_info = request.oidc_user.userinfo
# Access user_info['sub'], user_info['email'], etc.
# Your view logic

By default, mozilla-django-oidc looks up a Django user matching the email field to the email address returned in the user info data from Keycloak.

If a user logs into your site and doesn’t already have an account, by default, mozilla-django-oidc will create a new Django user account. It will create the User instance filling in the username (hash of the email address) and email fields.

Use Username rather than Email

mozilla-django-oidc defaults to setting up Django users using the email address as the user name from keycloak was required. Fortunately, preferred_username is set up by default in Keycloak as a claim. The claim can used by overriding the OIDCAuthenticationBackend class in mozilla_django_oidc.auth and referring to this in AUTHENTICATION_BACKENDS as below:


# Classes to override default OIDCAuthenticationBackend (Keycloak authentication)
from mozilla_django_oidc.auth import OIDCAuthenticationBackend

class KeycloakOIDCAuthenticationBackend(OIDCAuthenticationBackend):

def create_user(self, claims):
""" Overrides Authentication Backend so that Django users are
created with the keycloak preferred_username.
If nothing found matching the email, then try the username.
"""
user = super(KeycloakOIDCAuthenticationBackend, self).create_user(claims)
user.first_name = claims.get('given_name', '')
user.last_name = claims.get('family_name', '')
user.email = claims.get('email')
user.username = claims.get('preferred_username')
user.save()
return user

def filter_users_by_claims(self, claims):
""" Return all users matching the specified email.
If nothing found matching the email, then try the username
"""
email = claims.get('email')
preferred_username = claims.get('preferred_username')

if not email:
return self.UserModel.objects.none()
users = self.UserModel.objects.filter(email__iexact=email)

if len(users) < 1:
if not preferred_username:
return self.UserModel.objects.none()
users = self.UserModel.objects.filter(username__iexact=preferred_username)
return users

def update_user(self, user, claims):
user.first_name = claims.get('given_name', '')
user.last_name = claims.get('family_name', '')
user.email = claims.get('email')
user.username = claims.get('preferred_username')
user.save()
return user

In settings.py, overide the new library you have just added in AUTHENTICATION_BACKENDS :

 # mozilla_django_oidc - Keycloak authentication
"fragalysis.auth.KeycloakOIDCAuthenticationBackend",

Logging out

You can use the @oidc_logout decorator to log the user out of both your app and Keycloak:

from mozilla_django_oidc.decorators import oidc_logout

@oidc_logout
def logout_view(request):
# Your logout view logic

Add support for Django Rest Framework

Django Rest Framework (DRF) is a flexible toolkit built on top of Django, specifically designed for building RESTful APIs.

If you want DRF to authenticate users based on an OAuth access token provided in the Authorization header, you can use the DRF-specific authentication class which ships with the package.

Add this to your settings:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'mozilla_django_oidc.contrib.drf.OIDCAuthentication',
'rest_framework.authentication.SessionAuthentication',
# other authentication classes, if needed
],
}

Note that this only takes care of authenticating against an access token, and provides no options to create or renew tokens.

If you’ve created a custom Django OIDCAuthenticationBackend and added that to your AUTHENTICATION_BACKENDS, the DRF class should be smart enough to figure that out. Alternatively, you can manually set the OIDC backend to use:

OIDC_DRF_AUTH_BACKEND = 'mozilla_django_oidc.auth.OIDCAuthenticationBackend'

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 (password-less sign in), and Organization workflows.

· 4 min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 Next.js example. We also have a plain React 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 On.
    • Authorization to Off.
    • Standard flow checked. Direct access grants checked. All other items unchecked.
  9. Click Next.

    Keycloak OIDC Create Client Capability Config with Authentication

  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

  4. You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

    Keycloak OIDC Create Client Client Secret

Adding a Non-Admin User

Instructions
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 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 Next.js Project

info

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

This example uses Next.js 13 and splits server and client components accordingly.

  1. Clone the Phase Two example repo.

  2. Open the Next.js folder within /frameworks/nextjs.

  3. Run npm install and then npm run dev. This example leverages NextAuth.js to provide hook and HOC support.

  4. NextAuth.js configures an API route that is uses for the Authentication of the Client. It generates the routes automatically for you. These are added to Next.js in the api/auth/[...nextauth]/route.ts file.

  5. Open the src/lib/auth.ts file. This is a server only 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. While it is recommended to use Environment variables for the secret, for the purpose of this tutorial, paste in the Client secret from the OIDC client creation section for the value of clientSecret

    const authServerUrl = "https://euc1.auth.ac/auth/";
    const realm = "shared-deployment-001";
    const clientId = "reg-example-1";
    const clientSecret = "CLIENT_SECRET"; // Paste "Client secret" here. Use Environment variables in prod

    Those are used to popluate the AuthOptions config for the KeycloakProvider:

    export const AuthOptions: NextAuthOptions = {
    providers: [
    KeycloakProvider({
    clientId,
    clientSecret,
    issuer: `${authServerUrl}realms/${realm}`,
    }),
    ],
    };

    The config is then provided to the AuthProvider in the /src/app/layout.tsx file. Next.js uses this file to generate an HTML view for this page.

    import { NextAuthProvider as AuthProvider } from "./providers";
    ...
    <AuthProvider {...oidcConfig}>
    <App />
    </AuthProvider>

    At this point our entire application will be able to access all information and methods needed to perform authentication. View the providers.tsx file for additional information about how the SessionProvider is used. The SessionProvider enables use of Hooks to derive the authenticated state. View user.component.tsx for exactly how the code is authenticating your user. The sections rendering the "Log in" and "Log out" buttons are conditional areas based on the authenticated context. The buttons invoke functions provided by NextAuth.

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

  6. Open localhost:3000. 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.

  7. 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 their Token.

  8. After your first log in, click Log out. Then click Log in again. Notice how this time you will not be redirected to sign in as your state is already in the browser. 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 (password-less sign in), and Organization workflows.

· 3 min read

In this article we'll be using Keycloak to quickly augment an application with user management and SSO. 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 ReactJS 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
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 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 ReactJS Project

info

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

  1. Clone the Phase Two example repo.

  2. Open the ReactJS folder within /frameworks/reactjs.

  3. Run npm install and then npm start. This example leverages react-oidc-context (which uses oidc-client-ts) to provide hook and HOC support.

  4. Open the index.tsx 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.

    const authServerUrl = "https://euc1.auth.ac/auth/";
    const realm = "shared-deployment-001";
    const client = "reg-example-1";

    Those are used to popluate the OIDC config

    const oidcConfig = {
    authority: `${authServerUrl}realms/${realm}`,
    client_id: client,
    redirect_uri: "http://localhost:3000/authenticated",
    onSigninCallback: (args: any) =>
    window.history.replaceState(
    {},
    document.title,
    window.location.pathname
    ),
    };

    The config is then provided to the AuthProvider.

    <AuthProvider {...oidcConfig}>
    <App />
    </AuthProvider>

    At this point our entire applicationw will be able to access all information and methods needed to perform authentication. View Auth.tsx for exactly how the code is authenticating your user. The sections rendering the "Log in" and "Log out" buttons are conditional areas based on the authenticated context.

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

  5. Open localhost:3000. 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.

  6. 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 their Token.

  7. After your first log in, click Log out. Then click Log in again. Notice how this time you will not be redirected to sign in as your state is already in the browser. 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 (password-less sign in), and Organization workflows.

· 6 min read

There are a lot of guides out there, official and unofficial, for how to secure applications with Keycloak. The subject is rather broad, so it's difficult to know where to start. To begin, we'll be focusing on Keycloak's use of OpenID Connect (OIDC), and how to use that standard, along with some helpful libraries, to secure a simple but instructive application.

For the purposes of the sample, we'll actually be using two common applications, a frontend single-page application (SPA) written in JavaScript, and a backend REST API written for Node.js. The language we selected for the sample is JavaScript, but the principles apply no matter the implementation technology you choose.

What is OIDC?

When learning about identity and access management technologies, you'll be confronted with an alphabet-soup of acronyms to learn. OIDC, or OpenID Connect is one of the most important ones for securing applications, be it browser-based, APIs, mobile or native. Our friend over at OneLogin does a great job of explaining OIDC in plain english for those that are curious.

For the purpose of this guide, it is sufficient to know that OIDC is an open authentication protocol that works on top of the OAuth 2.0 framework. OIDC allows individuals to use single sign-on (SSO) to access relying party sites using OpenID Providers (OPs), such as an email provider or social network, to authenticate their identities. It provides the application or service with information about the user, the context of their authentication, and access to their profile information.

Login flow

A "flow" in OIDC terms is a mechanism of authenticating a user, and obtaning access tokens. The flow we'll be using in this guide is called the authorization code flow. Fortunately, the internals of the flow are not necessary to understand, as Keycloak handles the details for you.

However, it is useful to see what is going on in the login process, so that you understand your user's experience.

Keycloak Authentication Flow Diagram

Setup

We'll make an assumption for this guide that you are using a cloud deployment of Phase Two enhanced Keycloak. If you haven't already set one up, go over to the self-service launch announcement for details. You may also use your own Keycloak setup, but that setup is beyond the scope of this article.

The sample applications are available in our demo repo on Github. Clone that repo to your local machine. You'll find the applications in the frontend and backend directory, and a set of supporting files for configuration and deployment.

git clone https://github.com/p2-inc/debug-app.git
cd debug-app

Client

Every application that Keycloak protects is considered a Client. Log into your Keycloak realm, and click on Clients in the left navigation, and click Create client.

  1. Enter frontend as the Client ID and click Next
  2. In the Capability config screen, keep the defaults and click Save
  3. In the Access settings screen, enter the following values:
    1. http://localhost:3001/* for Valid redirect URIs
    2. + in Valid post logout redirect URIs
    3. + in Web origins
  4. Click Save
  5. In the upper right corner, open the Action menu and select Download adapter config. Click Download and move the file to the debug-app repo you cloned under the frontend folder.

Keycloak Client Details Setup Example

Make a user

Before we run the application, we need to create a user to log in. Click on Users in the left navigation, and click Add user. You only need to give the user a username and click Create. Find the Credentials tab and click Set password to give the user a password.

Running the sample apps

Open two terminal windows and go to the directory of the repo you cloned in both. To start, run the following commands in each terminal:

Frontend:

cd frontend/
npm install
npm start

Backend:

cd backend/
npm install
KC_REALM=<your-realm-name> KC_URL=<your-keycloak-url> npm start

Be sure to replace the realm name, and the URL of your Keycloak installation (e.g. https://usw2.auth.ac/auth/).

This will install the necessary components using npm, and will start the servers for both applications. Note: the applications use ports 3001 and 3002 by default. If you have other applications running on these ports, you may have to temporarily shut them down.

Putting it all together

Load http://localhost:3001/ in your browser. This will load the frontend application, which will be immediately redirected to the Keycloak login page. Log in with the user you created.

Once you log in, you'll see your profile, and several menu items. First click to the Access token menu item. You'll see the information from the parsed access token that was returned by Keycloak. This contains information about the user, but also claims related to the users roles and groups. This is because access tokens are meant to be read and validated by resource servers (i.e. our backend service).

Next, click ID token. You'll see similar information to what we saw in the access token, but limited to a standardized set of information that identifies the authentication state of the user. ID tokens are not meant for calling resource servers, and because of that, don't contain claims that are meant to be validated by backend services.

Clicking Service will call the backend service. You'll see a message that indicates the frontend called the backend, passing the access token, and was authorized to access a secured service.

You can also try the built-in Keycloak Account Management console by clicking Account, which gives the user a simple way to manage their information that is stored in Keycloak. It is not necessary to use this with your applications, as you may choose to build it in to your app. However, it's a good tool to have out of the box.

Finally, clicking Logout will take you back to the login page. This is actually sending you to the frontend's initial page, which is redirecting you to the login page as its default behavior.

What just happened?

There's a lot that goes into implementation of the OIDC flow we used to secure our sample applications. Part of the reason to use Keycloak is the mature implementation and client libraries that make protecting applications in a secure way almost trivial.

We encourage you to look at the source in the sample applications (specifically frontend/app.js and backend/app.js) and observe how the Keycloak client libraries are used to secure these applications. This will be a good place to start when you are working on securing your own applications.

Your application

Another incredible advantage to using standards like OIDC is that you are not constrained to using Keycloak libraries. Because your applications may not be written in JavaScript also, it's easy to use other language OIDC client libraries. We maintain a list of OIDC libraries, and the OpenID Foundation also maintains lists of certified and uncertified implementations

Today you saw how to quickly secure an application using Keycloak, and learned more about the underlying OIDC standards. We look forward to seeing what you build!