Vue
Follow this quickstart tutorial to add authentication to your Vue application
Last updated
Follow this quickstart tutorial to add authentication to your Vue application
Last updated
Authgear helps you add user logins to your Vue apps. It provides a prebuilt login page and user settings page that accelerate the development.
Follow this 15-minute tutorial to create a simple app using Vue with Authgear SDK.
Check out and clone the Sample Project on GitHub.
You need an Authgear account and a project to use Authgear. Sign up for a free account at https://portal.authgear.com/ and create a Project.
After that, we will need to create an Application in the Project Portal.
In this step, we'll create an Authgear client application in the Authgear Portal. We'll use the configuration for this application in later steps to connect our Vue application to Authgear.
To create a client application navigate to Applications on the left menu bar in Authgear Portal.
Next, click ⊕Add Application in the top toolbar to open the New Application page.
Input the name of your application, e.g. "MyAwesomeApp" then select Single Page Application as the Application Type.
Click Save to create the application.
On the next screen, you'll see links to tutorials for different frameworks. Click Next to skip to the application configuration page
The Redirect URI is a URL in your 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.
Scroll to the URI section of the configuration page for the client application you created in the last step. For this tutorial, add http://localhost:4000/auth-redirect
to Authorize Redirect URIs.
Click the Save button to save your changes before you proceed.
In this section, we'll add Authgear to a Vue application and use the Authgear JavaScript SDK to implement the following features:
User Login/Sign-up
Read logged-in user's info
Open User Settings page
End user session using a Logout button
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.
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.
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:
After doing so, when you run npm run dev
, the server will be running on port 4000.
Home.vue
fileCreate a new file called Home.vue
in the src/components
folder with simply showing Hello World
on the screen. Add the follow code to Home.vue
:
App.vue
fileThe App.vue
file is generated by Vite
already but some sections of it might not be needed for this tutorial. Edit the content of App.vue
to the following:
Some of the files might not be used and thus can be deleted. You can perform the following script to delete these files:
The file structure in your project is now:
Run npm run dev
now to run the project and you will see the default page with the title Vite + Vue
and a "Hello World" message on http://localhost:4000
.
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:
Run the following command within your Vue project directory to install the Authgear Web SDK
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. Your main.ts
file should look like this:
The Authgear container instance takes endpoint
and clientID
as parameters. They can be obtained from the application page created in Setup Application in Authgear.
Create a .env
file in the root directory of your project and add your Authgear client application configuration using the following fields:
It is recommended 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
Since we want to reference the logged-in state everywhere in the app, let's put the state in a context provider with UserProvider.vue
in the /src/contexts
folder.
In UserProvider.vue
, 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 has 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 automatically be set to true
. Finally, navigate back to root (/
) which is our Home page.
The final AuthRedirect.vue
will look like this
As we have already configured 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:
The file structure should now look like
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.
You can now run npm run dev
and you will be redirected to the Authgear Login page when you click the Login button.
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.
Run the app again, the User ID (sub) of the user should be printed on the Home page.
Finally, let's add a Logout button when a user is logged in.
In Home.vue
, we will add the following conditional elements in the template:
And add the logout
callback:
Run the app again, we can now log out by clicking the Logout button.
Authgear provides a built-in UI for the users to set their attributes and change security settings.
Use the open
function to open the settings page at <your_app_endpoint>/settings
In Home.vue
append a conditional link to the logout button section like this:
And add the userSetting
callback:
This is the resulting Home.vue
:
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 handles this, or you can get the token with authgear.accessToken
.
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 the refresh access token automatically. The authgear.fetch
implements fetch.
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.