Vue.js is an open source web framework that makes developing web applications easier.
In this article we'll be using Keycloak to secure a Vue.js Web application. 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.
Phase Two is a Keycloak as a Service provider enabling SaaS builders to accelerate time-to-market with powerful enterprise features like SSO, identity, and user management features. Phase Two enhances Keycloak through a variety of open-source extentions for modern SaaS use cases. Phase Two supports both hosted and on-premise deployment options.
What is Keycloak?
Keycloak has been a leader in the Identity and Access Management world since its launch almost 8 years ago. It is an open-source offering under the stewardship of Red Hat
INFO
If you just want to skip to the code, visit the Phase Two Vue.js example. We are also building Keycloak examples for other frameworks.
TOC
Setting up a Keycloak Instance
TIP
If you already have a functioning Keycloak instance, you can skip to the next section.
At this point, move on to the next step in the tutorial. We'll be coming back to the Admin Console when its time to start connecting our App to the Keycloak instance.Keycloak Setup Details
Rather than trying to set up a "from scratch" instance of Keycloak, we're going to short-circuit that process by leveraging a Phase Two free Keycloak starter instance. The Starter provides a free hosted instance of Phase Two's enhanced Keycloak ready for light production use cases.
Setting up an OIDC Client
We need to create a OpenID Connect Client in Keycloak for the app to communicate with.
Keycloak's docs provide steps for how to create an OIDC client and all the various configurations that can be introduced. Follow the steps below to create a client and get the right information necessary for app configuration. Under Login settings we need to add a redirect URI and Web origin in order. Assuming you are using the example application: Valid redirect URI (allows redirect back to application) Web origins (allows for Token auth call)Details
URI and Origin Details
The choice of localhost
is arbitrary. If you are using an example application running locally, this will apply. If you are using an app that you actually have deployed somewhere, then you will need to substitute the appropriate URI for that.
http://localhost:3000/*
http://localhost:3000
OIDC Config
We will need values to configure our application. To get these values follow the instructions below.Details
Adding a Non-Admin User
INFO
It is bad practice to use your Admin user to sign in to an Application.
Since we do not want to use our Admin user for signing into the app we will build, we need to add another non-admin user.
Details
Setting up a Vue.js Project
- Clone the Phase Two example repo.
- Open the Vue folder within
/frameworks/vue
and open the/nuxt/oidc-client-ts
folder. - Run
npm install
and thennpm run dev
. - 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 theclientSecret
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);
- 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.
- 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 theAuth
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.
- 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.
Top comments (0)