DeelesiEmmanuel
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Authenticating Vue Apps with Okta Securing user access and data privacy is paramount in today’s digital landscape. In Vue.js applications, authentication is pivotal in safeguarding user identities and enhancing application security. As developers strive to create seamless user experiences, effective authentication mechanisms are essential to streamline login processes, enable Single Sign-On (SSO), and efficiently manage user access. This article delves into the significance of authentication in Vue apps, exploring how implementing robust authentication solutions like Okta can resolve challenges related to user identity, data protection, and seamless user journeys. ## What is Okta Okta is a cloud-based platform for authentication and authorization. In contrast to other identity platforms, Okta seamlessly integrates with both on-premises and cloud apps. ### Why use Okta Okta is a valuable choice for authentication due to its robust security features, enabling secure user access. It streamlines the authentication process through Single Sign-On (SSO), enhancing user experience and reducing password management burden. Okta's developer-friendly SDKs simplify integration into Vue applications, ensuring efficient implementation. Its support for identity federation and compliance aids seamless integration and adherence to regulations. ## Prerequisites To follow this tutorial, you should have the following: - Knowledge of Javascript. - Knowledge of Vue. - [Vue CLI](https://cli.vuejs.org/guide/installation.html) installed. ## Setting up Okta Let’s get started with creating an Okta account. Click on this [link](https://developer.okta.com/) to create one. After creating your Okta account, you will be redirected to the admin dashboard. On the admin dashboard, click on the “Applications” tab and then on “Create App Integration.” ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692451395609_Screenshot+2023-08-19+at+11.16.04.png) Next, select “OIDC - OpenID Connect,” then click “Single-Page Application” and Next. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692453142729_Screenshot+2023-08-19+at+11.17.19.png) Next, add your app integration name and logo(optional), then leave everything else at default. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692451487296_Screenshot+2023-08-19+at+11.18.21.png) Next, scroll down to the end of the modal and select “Allow everyone in your Next, scroll down to the end of the modal and select “Allow everyone in your organization to access,” then Save. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692451473201_Screenshot+2023-08-19+at+11.18.57.png) Finally, copy and save the Client ID and the Issuer Address at the dashboard's top right corner. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692453478848_Screenshot+2023-08-19+at+11.19.39.png) **Creating Okta Users.** Now that the app is all set let’s create some users that can interact with our app. Head to your Okta admin dashboard and click “Directory > People” in the sidebar. Next, click on “Add Person”. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692451395565_Screenshot+2023-08-19+at+11.20.45.png) Then, fill in the user’s details, as seen below, and save. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692453935826_Screenshot+2023-08-19+at+11.25.39.png) ## Setting up Work Environment With the Okta Authenticator set up, let’s scaffold our Vue app using the [Vue CLI](https://cli.vuejs.org/guide/installation.html) tool. Run the command below in the terminal. ``` vue create Vue-auth ``` Next, Select the setup shown In the image below. ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692454718411_Screenshot+2023-08-19+at+15.18.35.png) ### Installing Packages We’ll use the [Okta/okta-auth-js](https://www.npmjs.com/package/@okta/okta-auth-js?activeTab=readme) and the [Okta/okta-vue](https://www.npmjs.com/package/@okta/okta-vue) package for this project. To install these, change the directory to the project folder and install the above packages using the command below. ``` cd vue-auth && yarn add @okta/okta-vue @okta/okta-auth-js ``` Or using Npm ``` cd vue-auth && npm i @okta/okta-vue @okta/okta-auth-js ``` ### Building Authentication UI Let’s start building our Vue app. Head to the `main.js` in the `src/` folder and replace the code below. ```javascript /* eslint-disable */ import { createApp } from 'vue' import { OktaAuth } from '@okta/okta-auth-js' import OktaVue from '@okta/okta-vue' import App from './App.vue' import router from './router' const oktaAuth = new OktaAuth({ clientId: `${Your_ClientId}`, issuer: `https://${Your_Issuer_Address}/oauth2/default`, redirectUri: `${window.location.origin}/login/callback`, scopes: ['openid', 'profile', 'email'] }); createApp(App) .use(router) .use(OktaVue, { oktaAuth }) .mount('#app') ``` In the code above, we’re setting up the Okta authentication in our Vue.js application by configuring the `OktaAuth` instance, registering the `OktaVue` package, and setting up routing into the Vue DOM. In the `OktaAuth` object, we’re assigning our Client ID and Issuer Address that we copied from the Okta dashboard. We’ve also ensured the `redirectUri` path is identical to the one on our Okta console. Next, head over to the `App.vue` in the `src/` folder and replace the code in it with the code below. ```jsx <template> <main id="app"> <router-view /> </main> </template> <style> * { margin: 0; padding: 0; box-sizing: border-box; } #app { padding: 3rem; color: whitesmoke; background-color: black; height: 110vh; } button { color: red; box-shadow: 0 5px 8px 0 rgba(115, 115, 115, 0.24), 0 7px 20px 0 rgba(72, 72, 72, 0.19); background-color: #4caf50; /* Green */ border: none; color: white; padding: 12px 28px; text-align: center; text-decoration: none; display: inline-block; font-size: 19px; } </style> ``` In the code above, we render the Vue router components and create custom styles for our pages and button. ```jsx import { createRouter, createWebHistory } from "vue-router"; import { LoginCallback } from "@okta/okta-vue"; import HomeView from "@/views/HomeView"; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes: [ { path: "/", component: HomeView, }, { path: "/login/callback", component: LoginCallback, }, ], }); export default router; ``` In the code above, we’re rending the `HomeView` component as our default and home component. Then we display the `LoginCallback` component from the `okta-vue` package as our redirect Component when we log in. This component handles our login state by storing our login token in the Local storage. Next, Create a `HomeView.vue` app in the `src/views/` folder, and paste the code below into it. ```jsx <template> <main> <div v-if="!authState?.isAuthenticated"> <h1>Welcome To HomePage</h1> <br /> <p> 🌟 Welcome to our Home Page! 🌟 We're excited to have you here. To get started on your journey, simply click the button below to initiate the secure login process. Our seamless integration with Okta ensures your information is well-protected while granting you access to all the amazing features that await you. Click to Login and Explore ➡️ 🚀🔐 </p> <br /> <button>Login</button> </div> </main> </template> ``` In the code above, we’re rending the welcome message and a Login button when the user is authenticated. ## Authenticating App with Okta With our set up complete, let’s write our authentication logic. Head to the `HomeView.vue` file and paste the code below the `</template>` tag. ```jsx <script> export default { name: "HomeView", data: function () { return { userData: null, userClaims: [], }; }, async created() { this.userDetails(); }, methods: { async userDetails() { if (this.authState?.isAuthenticated) { const authToken = await this.$auth.tokenManager.get("idToken"); this.userArray = await this.$auth.getUser(); this.userClaims = Object.entries(authToken.claims).map( ([claimType, claimValue]) => ({ claimType, claimValue, }) ); } }, async userLogout() { await this.$auth.signOut(); }, async userLogin() { await this.$auth.signInWithRedirect(); }, }, }; </script> ``` In the code above, we’re managing the user’s authentication and details using the Okta authentication service. When the component is created, the user details are fetched and assigned to the `userData` and `userClaims` values if the user is authenticated. Finally, we also created the user’s login and logout functions. ### Integrating Okta Auth Logic Let’s add the `userLogin` function to our Login button in our `HomeView` template. ```jsx <button id="login-button" v-on:click="login">Login</button> ``` Finally, let’s inject our auth logic into our template. For this, we’ll display a welcome message with the user’s name and a table containing the user’s login information. To achieve this, paste the code below into the `<template>` tag below the first closing `div`. ```jsx <div v-if="authState?.isAuthenticated"> <h1>Welcome {{ userData && userData.name }}!</h1> <br /> <p> 🎉 Congratulations! 🎉 You're now successfully logged in to your account. We're thrilled to have you as part of our community. Your journey starts here, and we're here to support you every step of the way. To below is your account details. 🔍 🌟🔐 </p> <br /> <div> <h1>User Information</h1> <br /> <table class="detail-table"> <thead> <tr> <th>Properties</th> <th>Value</th> </tr> </thead> <tbody> <tr v-for="(x, index) in userClaims" :key="index"> <td>{{ x.claimType }}</td> <td :id="'id-' + x.claimType">{{ x.claimValue }}</td> </tr> </tbody> </table> <br /> <button class="logoutBtn" v-on:click="userLogout">Logout</button> </div> </div> ``` The code above displays user information when the user is authenticated. It includes a welcome message, user details in a table, and a logout button. Also, in the code above, we’re using Vue's directives (`v-if`, `v-for`) to dynamically display the content based on the user's authentication status and provided user claims. To preview what we’ve done, run the command below in the project terminal. ``` vue serve ``` ![](https://paper-attachments.dropboxusercontent.com/s_F7D69AE07024D8A0332CF022AD1AF0E83FFC996C89BEADE4BB1FC21BFE4D8F5D_1692469070002_ezgif.com-video-to-gif+1.gif) ## Conclusion In this article, we’ve seen how to set up an Okta Single Page Application authentication and authenticate users into our application using the [Okta/okta-auth-js](https://www.npmjs.com/package/@okta/okta-auth-js?activeTab=readme) and the [Okta/okta-vue](https://www.npmjs.com/package/@okta/okta-vue) packages. By leveraging the power of Okta's advanced authentication capabilities, developers can ensure data integrity and user trust while seamlessly implementing secure user experiences. Here is the link to the [complete source code](https://github.com/iamVictorSam/vue-auth) on GitHub. ## Resources - [Okta Vs. Other Authentication Managers](https://blog.openreplay.com/okta-vs-other-auth-managers/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully