Skip to main content

29 posts tagged with "phase_two"

View All Tags

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

· 4 min read

We're excited today to announce the launch of our dedicated clusters offering. Our Phase Two enhanced Keycloak distribution is now available as a hosted, dedicated cluster in the region of your choice.

About 9 months ago, we launched our self-service, shared deployments, offering customers the ability to create Phase Two enhanced Keycloak realms on our shared clusters. Over that period, we've provided over 700 free realms for testing and small production use cases. Many of you have reached out to us asking about an SLA, isolated resources, and ability to grow into larger use cases. Based on your requests and feedback, we built out our dedicated cluster offering.

What is Phase Two again?

Phase Two helps SaaS builders accelerate time-to-market and enterprise adoption with powerful SSO, identity and user management features. To that end, Phase Two has created an enhanced distribution of Keycloak that bundles several essential open source extensions for modern SaaS use cases. We support hosted and on-prem customers for a variety of use cases.

Why dedicated?

Dedicated clusters allow us to provide compute, network and storage isolation for customer workloads, and to easily deploy in the region where customer's users are. With dedicated clusters, we can guarantee an SLA that meets customer's needs with no resource contention from other customers.

Furthermore, it allows us to support customer-provided domain names, and access to monitoring and management capabilities not available in the shared clusters.

How did you do it?

We built out our dedicated cluster offering using the best-of-breed open source tools and managed services.

The core consists of Kubernetes clusters in each supported AWS and GCP region. New dedicated clusters are provisioned instantly using FluxCD, a continuous delivery solution that gives us the history and auditability of git. Monitoring and alerting is done using Prometheus, Grafana, and a suite of external services that give us a complete view of cluster health.

The database tier uses a managed CockroachDB service provided by Cockroach Labs. Phase Two is the only provider that is capable of hosting the current Keycloak distribution (the "legacy" store) using CockroachDB. Working with Cockroach Labs gives us the expertise and reliability from hosting thousands of customer clusters at massive scale.

Take me to it!

Starting today, you'll be able to log into the updated dashboard, and create your dedicated cluster by selecting a region and setting up your billing information.

Keycloak Phase Two Self-Host Cluster Creation

Following successful billing setup, you will be returned to the Dashboard while your Cluster is provisioned. Once provisioned, you'll be able to create up to 20 realms per cluster, using the same easy setup as you are used to in the shared deployment offering.

Keycloak Phase Two Self-Host Cluster Creation Status

Most clusters will be provisioned within 30 minutes, but some requests may take up to 24 hours. Additionally, for payment types such as ACH or SEPA, cluster provisioning will begin following payment clearing (up to 4 days in some cases).

How much does it cost?

Plans start at $499US per month when paid annually. This provides a set of compute, network and storage resources that have been tested for common use cases for up to 20 realms and 1 million users. If your use case is uncommon or you plan to scale beyond that, our system is designed to scale up with your needs. Our plans scale linearly with resource demands beyond our minimums.

We will continue to support a robust Free tier.

What's next? (psst... Global clusters)

Many of our on-prem, suppport customers with large use cases asked us to build out a solution for massive-scale, fault-tolerant, multi-region use cases. One of the great parts of building support for Keycloak's existing storage system for CockroacDB is that we've been able to explore use cases that were previously impossible using the standard Keycloak distribution, or required complex, error-prone configurations. For use cases with these requirements, plus global proximity to users and regional failover, we built global clusters, backed by CockroachDB multi-region database, for which we are now in beta.

These clusters provide a minimum of 3 global regions, with 3 instances of Phase Two enhanced Keycloak per region. Global server load balancing provides geographic region affinity and failover to connect your users with the closest, available instances.

There will be two price tiers for global clusters, depending on your use of our shared CockroachDB clusters, or your own dedicated clusters. We expect to launch general availability of global clusters later in Q3 2023.

Please contact sales@phasetwo.io to talk to us about your global cluster use case.

· 3 min read

Brand is important to modern SaaS companies, and nowhere is that more apparent than at the front door: the login experience. Unfortunately, the default design of the Keycloak login experience has a "face only a mother could love".

In order to allow customers to customize that experience, we've extended the default Keycloak theming functionality to allow you to easily customize the login pages from the admin console. This eliminates the need to package and deploy a custom theme, and allows fast iteration without restart.

Simple customization

If you're in a hurry, logo and color customization can be achieved by adding your logo's URL and three color choices. These are available in the General and Login tabs of the Styles section.

Keycloak Phase Two Login Page Customization Logo URL

Keycloak Phase Two Login Page Customization Styles Configuration

In order for these setting to take effect, your Realm Settings Themes must also be set to Attributes for the Login theme type

Keycloak Phase Two Login Page Theme Setting

Full customization using CSS

Many of you will have more stringent branding requirements. For this, you can override the styles of the default Keycloak login theme. To discover the base styles that are available using this theme, we recommend

Note that using CSS overrides will cause the colors from simple customization not to work.

In order to load your CSS, paste it into the "CSS" field in the Login tab of the Styles section.

Keycloak Phase Two Login Page Custom CSS

This CSS will be the last CSS loaded, overridding the styles in the default keycloak login theme.

References:

CSS Examples

To get you started with some ideas, we've created 3 example login themes that were done by overridding the CSS. These are free of license restriction, so feel free to download, use and customize the CSS at the links with the example images.

Images and other assets

You'll notice that images, icons and fonts not found in the standard Keycloak themes are used. These are referenced by URL in the CSS. For example, if you are used to loading a custom font in the <head> of your HTML, it is possible to do it in CSS using @import:

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Lexend+Deca:wght@300;400;500;600;700&family=Lexend:wght@300;400;500;600;700&family=Work+Sans:wght@300;400;500;600;700&display=swap");

And background and other images can be referenced by their full URL using url(...):

.login-pf body {
background-image: url("https://raw.githubusercontent.com/p2-inc/keycloak-themes/main/examples/saas/assets/SaaS%20BG.webp");
}

Success!

As always, our success is based on the success of our customers. We hope this extension and guide has helped you update the default Keycloak login branding to match that of your needs. If you have suggestions for further improvement of this feature, please reach out on GitHub!

· 2 min read

tl;dr

We’ve changed the license of our core extensions from the AGPL v3 to the Elastic License v2. We wanted to share why we made this change and what it means for our customers and community.

Why?

From our earliest stages, Phase Two has been built as a set of extensions to Keycloak. We have made a commitment that source code for our core exetensions will always be available so that our customers can migrate to their own deployment, while maintaining the extension functionality provided by Phase Two.

As our product matured and found a market fit, it became clear to us that our current license was failing to give our customers that guarantee, and failing to give our company the protection to ensure we could build a business and continue to invest in our extensions.

We've had some very deep conversations with customers and contributors about the future of licensing, and learned a lot about what other companies in our shoes have done. We truly appreciate all of the engagement and feedback, and have done our best to make a decision that is in the best interest of our company, customers and community.

What's allowed?

  1. Hosting and using the extensions by companies as part of their own product.
  2. Derivative works that maintain the same license.

What's prohibited?

  1. Providing the extensions as a hosted or managed service. This includes bundling and distribution by companies who sell their products for on-prem and private cloud use.

We believe that the Elastic License strikes a great balance, and we're excited for our next phase of growth!

· 4 min read

We've received a lot of support requests about the right way to set up SSO connections. We've published a 5 minute video showing you how to do it easily. Also, the script is included below in case you miss anything!

Script

Developers have been asking for concise setup instructions for SSO. You’re here for our enterprise SSO functionality. We hear you. Here’s a quick live setup to show you how easy it is.

I’m assuming you have already created a self-serve deployment.

  • Start by opening the console.
  • Navigate to the Organizations tab.
  • Create a new organization. In this case, set a domain when creating an organization that corresponds to the email domains you want to match to their SSO provider.
  • Create a Portal Link by selecting it from the action menu of the organization. This is usually meant to be sent to the organization administrator, but in this case, we’ll open this link in an incognito window and configure the identity provider ourselves.

We’ll use the identity provider wizard to setup a SSO connection to Azure AD. I’ve sped this up a bit, but you’ll get an idea of what is happening. Depending on your setup and target identity provider, this will be different.

Now let’s secure an application and use our new SSO connection to log in. For this purpose, we’ve got a debugging application on Github you can use to quickly see how a front end application is secured and what data is shared between Phase Two and the application.

  • Clone our debug-app from github, and open up the frontend folder in your favorite editor or IDE.
  • Go back to the admin console and navigate to the Clients tab. Create a new client. Let’s call it frontend. This will be a public OIDC client, with localhost:3001 as the root and redirect uri.
  • Get the keycloak.json from the configuration and copy it. Paste it into keycloak.json to configure your debug-app.

Before we continue, we need to configure an authentication flow that does our SSO redirect.

  • Navigate to the Authentication tab, and duplicate the Browser flow.
  • Add the Home IdP Discovery authenticator and move it into the position before the user forms. Configure it to not require a verified domain nor email.
  • Finally, using the action menu, bind it to the browser flow.

Go back to the debug-app, and let’s try a login using an email domain that matches the one we configured.

  • First, run npm i and npm start to start the debug app, and navigate to http://localhost:3001 in your browser. See that it redirects to the default login.
  • Enter the email address in the new email only form.
  • We are redirected to the Azure identity provider we set up.
  • Log in to Azure, and then we are redirected to back to debug-app.
  • Let’s take a look at the token and see the data that came over from Azure.

As a bonus, let’s map some information about the user’s organization memberships into the token in case we need to do something with that information in our application.

  • Go back to the Admin UI and navigate to the Client we created.
  • Select the frontend-dedicated client scope.
  • Add a mapper by configuration.
  • Select the Organization Role mapper and configure it as shown.
  • Save the configuration.

Now let’s go back to the debug-app and reload.

  • Take a look at the token. It now contains information about the organization we created.
  • The user was automatically created and added as a member to the organization when we logged in through the Azure identity provider.

You now have a fully working authentication and enterprise SSO setup for your application. It took about 5 minutes!

· 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!

· 6 min read

Someone who is reading this article is probably very different that the average internet user when it comes to passwords. Developers and IT admins, either because of security savvy or compliance, use password managers, multi-factor authentication (MFA) mechanisms, or prefer sites that offer password-less authentication. Furthermore, they are keenly aware of the weaknesses in their personal "attack surface", and search for ways to balance convenience with risk.

But you are here because you want to find a way to implement magic links quickly. First, some background.

Magic links are a type of password-less authentication that allow your users to log in to your application following a link that is emailed to them, rather than typing a username and password. Magic links can also be used as a part of a multi-factor authentication (MFA) strategy.

In a magic link flow, the application's authentication provider asks users for an email address rather than a password. The authentication provider generates a link with an embedded token, and sends to the user's email. There may be some other steps taken by the provider, such as verifying the provided email address matches an existing user. The user then opens the email, clicks the link, is verified by the authentication provider, and is granted access to the application

Keycloak Phase Two Magic Link Extension Flow Diagram

Pros and cons

Like any mechanism that tries to streamline a security process such as authentication, there are both pros and cons to the magic link approach. First in the plus column:

  • Enhances user experience, which makes users more likely to use your application, and be satisfied with the experience. This drives user engagement.
  • User onboarding is accelerated, as magic links can be sent to new users as well as existing ones. Registration for your application is as easy as entering your email address.
  • You'll never have a password breach. When there are no passwords, there are no password breaches. A huge number of corporate data breaches are due to insufficient and compromised passwords.
  • No more customer support requests related to lost passwords. Over half of customer support requests are due to authentication problems, many of those are users unable to remember their passwords. This eliminates a huge portion of those.

Nothing is perfect, and there are also several potential downsides to magic links:

  • Account security and access are now tied to the security of the user's email account. If the user's computer or other device is compromised, and attacker could potentially obtain the link and impersonate the user.
  • If the user or email provider does not enforce encrypted network access to email, it may be possible for an attacker to perform a man-in-the-middle attack where they can obtain the link by observing network traffic.
  • Ability to access your application is now tied to email deliverability. If your email service or the user's email provider fails to deliver the email containing the link in a timely fashion, it could deteriorate the experience for the user.

Limiting risk

Fortunately, there are things your application and the user can do in order to limit some of the possible downside risks of using magic links. Your application can:

  • Make the magic links single use, or set a very short expiration time for the links.
  • Enforce an additional factor when using magic links.

Your user can:

  • Choose an email provider that enforces the use of encrypted connections.
  • Use multi-factor authentication (MFA) mechanisms to further protect their email accounts.

Setup guide

Sorry for the wait! We wanted to give you an overview of magic links before diving into how to set them up with Phase Two.

If you haven't already, get an account on Phase Two. You'll notice that we use magic links in addition to social login options. As we said above, we're trying to make it as frictionless as possible to get in and start using the product.

Once you log in and create your first deployment, open the Phase Two enhanced Keycloak console. In order to email links to your users, you'll need to set up email. If you haven't already done that, head over to our email setup guide.

After you've completed email setup, select the Authentication menu item, and then select the Magic link flow from the list.

Keycloak Phase Two Magic Link Authentication Page Flow Name

Open the configuration for the Magic Link Authenticator by clicking the gear icon on the last line with the Magic Link execution. You'll notice two options:

  • Force create user creates a new user when an email is provided that does not match an existing user. This allows the use of magic links to register new users that have not been previously seen.
  • Update profile on create adds an UPDATE_PROFILE required action if the user was created. This means that the user will need to fill out other required fields such as first/last name, etc.

For the purpose of our demonstration, let's set Force create user to ON and Update profile on create to OFF (remember, low friction). Save the configuration, and go back to the flow page.

In the Action menu of the flow page, select Bind, and select Browser flow.

Keycloak Phase Two Magic Link Bind Flow

Now you're ready to test it out. If you don't have an application that is setup and protected by Keycloak, you can use the built-in account console to try it out. Navigate to the Clients menu, and open the link next to the account client in an incognito window (this will prevent conflict, as you are already logged in to the admin console as the administrator).

Click Sign In and you'll be redirected to the authentication page. Enter your email address, and you'll be sent a magic link. Click on the link in your email, and you'll see your details in the account console.

Keycloak Phase Two Magic Link Login Page Keycloak Phase Two Magic Link Confirm Page

Go back to the admin console in the other browser window, and navigate to the Users section. You will be able to find the user that was just created.

Keycloak Phase Two Magic Link Admin User View

Magic links are a great way to streamline your user onboarding and experience to help you easily drive engagement across your application. Phase Two makes it quick and easy to integrate magic links (and social login, and enterprise SSO, and much more). Stay tuned for more guides that will help you build the authentication experience that is right for your app.

· 3 min read

One of the first things you will need to do when getting a Keycloak Realm ready for use is to set up your email server configuration. There are many system emails that are sent to users in the course of verifying and updating user accounts: Email address verification, magic links, password reset, account update, login failure notifications, identity provider linking, etc.

In order to provide your users with a positive experience, these messages need a way to get to them. Keycloak supports any internet reachable SMTP server. If you are currently testing, and don't have an email server or service that you currently use, SendGrid provides free accounts that allow you to send up to 100 emails per day forever. For debugging, you can also use a service like MailTrap to give you a catch-all for emails coming from Keycloak.

If you are using a Phase Two Deployment, log in to the self-service dashboard, and click on the Open Console link for the Deployment you wish to use. Once in the Keycloak admin console, click Realm settings in the left menu, and then click the Email tab.

Keycloak Email Configuration

In the first section, labeled Template, you will set options that will be used in the templates for the emails that are sent to your users. The only required field is the From field, which must contain the email address the user will see the email originating from. This should be an email address that your email server is expecting, and it will not block for authorization reasons.

The other fields in the Template section are not required, but will enhance how your emails look:

  • From address used to send emails (required)
  • From display name a user-friendly name displayed along From
  • Reply to an email address that will be used by email clients when your user replies to an email
  • Reply to display name a user-friendly name displayed along Reply to
  • Envelope from Bounce Address used for the mails that are rejected

Keycloak Email Server Connection and Authentication

In the Connection & Authentication section, you will provide details of your SMTP server:

  • Host indicates the SMTP server hostname used for sending emails
  • Port indicates the SMTP server port (usually 25, 465, 587, or 2525)
  • Encryption support encryption for communication with your SMTP server
  • Authentication if your SMTP server requires authentication, and supply the Username and Password

Keycloak email setup buttons

Finally, before you click Save, click the Test connection button to send a test email to the email address of the currently logged in user. If you don't have that set, you might have click Save and edit your user before you come back. You'll receive a success message, or information that will help you resolve problems.

Once you do that, you'll have accomplished a significant task which enables lots of other functionality!

Also, stay tuned for another post on how to customize your email templates to match your branding and messaging.