After that, we will need to create an Application in the Project Portal.
Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application, e.g. "MyAwesomeApp".
Select Single Page Application as the application type
Click "Save" to create the application
Configure Authorize Redirect URI
The Redirect URI is a URL in you application where the user will be redirected to after login with Authgear. In this path, make a finish authentication call to complete the login process.
For this tutorial, add http://localhost:4000/auth-redirect to Authorize Redirect URIs.
Configure Post Logout Redirect URI
The Post Logout Redirect URI is the URL users will be redirected after they have logged out. The URL must be whitelisted.
For this tutorial, add http://localhost:4000/ to Post Logout Redirect URIs.
Save the configuration before next steps.
Step 1: Create a simple Vue project
Here are some recommended steps to scaffold a Vue project. You can skip this part if you are adding Authgear to an existing project. See Step 3: Install Authgear SDK to the project in the next section.
Install basic project dependencies
Create the project folder and install the dependencies. We will use vite as the build tool and the vue-router package. Also, we will use TypeScript in this tutorial.
# Create a brand new project using vitenpmcreatevite@latestmy-app----templatevue-ts# Move into the project directorycdmy-app# Install dependenciesnpminstall# Install vue-routernpminstall--save-exactvue-router
Add port configuration for development mode
As we are using port 4000 for this tutorial, we need to add the port information to the config. In the vite.config.ts file, modify the file with the following lines:
Run npm run dev now to run the project and you will see default page with the title Vite + Vue and a count button on http://localhost:4000.
Step 2: Create routes for the project
Create a AuthRedirect.vue file in the src/components folder with the same content as src/components/Home.vue at this moment.
Create a file called router.ts in the src/ folder. We will import Home and AuthRedirect component as the route and we will implement these components later. The content of this file will look like this:
// src/router.tsimport { createRouter, createWebHistory } from"vue-router";exportconsthistory=createWebHistory();exportconstrouter=createRouter({ history, routes: [ { path:"/",// We will implement this component latercomponent: () =>import("./components/Home.vue"), }, { path:"/auth-redirect",// We will implement this component latercomponent: () =>import("./components/AuthRedirect.vue"), }, ],});
Step 3: Install Authgear SDK to the project
Run the following command within your Vue project directory to install the Authgear Web SDK
npminstall--save-exact@authgear/web
In src/main.ts , import authgear and call the configure function to initialize an Authgear instance on application loads. We will also import router and use it to build routes for us.
The Authgear container instance takes endpoint and clientID as parameters. They can be obtained from the application page created in Setup Application in Authgear.
It is recommend to render the app after configure() resolves. So by the time the app is rendered, Authgear is ready to use.
Run npm run dev now and you should see the same page and no error message in the console if Authgear SDK is configured successfully
Step 4: Implement the Context Provider
Since we want to reference the logged in state in anywhere of the app, let's put the state in a context provider with UserProvider.vue in the /src/contexts folder.
In UserProvider.vue, it will have a isLoggedIn boolean value. The isLoggedIn boolean state can be auto updated using the onSessionStateChange callback. This callback can be stored in delegate which is in the local SDK container.
Next, we will add an "AuthRedirect" page for handling the authentication result after the user have been authenticated by Authgear.
Create the AuthRedirect.vue component file in the src/components/ folder.
Call the Authgear finishAuthentication() function in the Auth Redirect component to send a token back to Authgear server in exchange for access token and refresh token. Don't worry about the technical jargons, finishAuthentication() will do all the hard work for you and and save the authentication data.
When the authentication is finished, the isLoggedIn state from the UserContextProvider will automatic set to true. Finally, navigate back to root (/) which is our Home page.
The final AuthRedirect.vue will look like this
// src/components/AuthRedirect.vue<scriptsetuplang="ts">import { onMounted } from "vue";import authgear from "@authgear/web";import { router } from "../router";onMounted(() => {asyncfunctionupdateToken() {try {awaitauthgear.finishAuthentication(); } finally {router.replace({ path:"/" }); } }updateToken().catch((e) =>console.error(e));});</script><template></template>
Step 6: Apply Routes and Context Provider to the App
As we have already configure the routes in the previous section, we can simply add <router-view /> tag to the App.vue. We can then Import UserProvider and wrap the router-view with it.
Your final App.vue should look like this:
// src/App.vue<scriptsetuplang="ts">import UserProvider from "./contexts/UserProvider.vue";</script><template> <UserProvider> <router-view /> </UserProvider></template>
First we will import the Authgear dependency. Then add the login button which will call startAuthentication(ConfigureOptions) through startLogin callback on click. This will redirect the user to the login page.
// src/components/Home.vue<scriptsetuplang="ts">import authgear from "@authgear/web";const startLogin = () => { authgear.startAuthentication({ redirectURI:"http://localhost:4000/auth-redirect", prompt:"login", }).then( () => {// started authorization, user should be redirected to Authgear }, (err) => {// failed to start authorizationconsole.error(err); } );};</script><template> <h1>Home Page</h1> <button @click="startLogin">Login</button></template>
You can now run npm run dev and you will be redirected to the Authgear Login page when you click the Login button.
Step 8: Show the user information
The Authgear SDK helps you get the information of the logged in users easily.
In the last step, the user is successfully logged in so let's try to print the user ID (sub) of the user in the Home page.
In Home.vue, we will add a simple Loading splash and a greeting message printing the Sub ID. We will add two conditional elements such that they are only shown when user is logged in. We can also change the login button to show only if the user is not logged in.
Make use of isLoggedIn from the UserProvider to control the components on the page. Fetch the user info by fetchInfo() and access its sub property.
The Login button can be also rendered conditionally which only visible if the user is not logged in.
// src/components/Home.vue <scriptsetuplang="ts">import authgear from "@authgear/web";import { inject, onMounted, ref } from "vue";import { UserStateSymbol } from "../contexts/UserProvider.vue";const { isLoggedIn } = inject(UserStateSymbol)!;const isLoading = ref(false);const greetingMessage = ref("");onMounted(() => {asyncfunctionupdateGreetingMessage() {isLoading.value =true;try {if (isLoggedIn.value) {constuserInfo=awaitauthgear.fetchUserInfo();greetingMessage.value ="The current User sub: "+userInfo.sub; } } finally {isLoading.value =false; } }updateGreetingMessage().catch((e) => {console.error(e); });});const startLogin = () => { authgear.startAuthentication({ redirectURI:"http://localhost:4000/auth-redirect", prompt:"login", }).then( () => {// started authorization, user should be redirected to Authgear }, (err) => {// failed to start authorizationconsole.error(err); } );};</script><template> <h1>Home Page</h1> <spanv-if="isLoading">Loading...</span> <spanv-if="greetingMessage">{{ greetingMessage }}</span> <divv-if="!isLoggedIn"> <button @click="startLogin">Login</button> </div></template>
Run the app again, the User ID (sub) of the user should be printed on the Home page.
Step 9: Add a Logout button
Finally, let's add an Logout button when user is logged in.
In Home.vue, we will add a conditional elements in the template:
To access restricted resources on your backend application server, the HTTP requests should include the access token in their Authorization headers. The Web SDK provides a fetch function which automatically handle this, or you can get the token with authgear.accessToken.
Option 1: Using fetch function provided by Authgear SDK
Authgear SDK provides the fetch function for you to call your application server. This fetch function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch implements fetch.
Option 2: Add the access token to the HTTP request header
You can get the access token through authgear.accessToken. Call refreshAccessTokenIfNeeded every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.
authgear.refreshAccessTokenIfNeeded().then(() => {// access token is ready to use// accessToken can be string or undefined// it will be empty if user is not logged in or session is invalidconstaccessToken=authgear.accessToken;// include Authorization header in your application requestconstheaders= { Authorization:`Bearer ${accessToken}` }; });