Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@okta/okta-vue

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@okta/okta-vue

Vue support for Okta

  • 2.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

Okta Vue SDK

npm version build status

Okta Vue SDK builds on top of the Okta Auth SDK. This SDK integrates with the vue-router and extends the Vue prototype with an Auth service to help you quickly add authentication and authorization to your Vue single-page web application.

With the Okta Auth SDK, you can:

  • Login and logout from Okta using the OAuth 2.0 API
  • Retrieve user information
  • Determine authentication status
  • Validate the current user's session

All of these features are supported by this SDK. Additionally, using this SDK, you can:

  • Add "protected" routes, which will require authentication before render
  • Provide an instance of the Auth service to your components on the Vue prototype

This SDK does not provide any UI components.

This SDK does not currently support Server Side Rendering (SSR)

This library currently supports:

Getting Started

  • If you do not already have a Developer Edition Account, you can create one at https://developer.okta.com/signup/.
  • An Okta Application, configured for Single-Page App (SPA) mode. This is done from the Okta Developer Console and you can find instructions here. When following the wizard, use the default properties. They are are designed to work with our sample applications.

Installation

This library is available through npm. To install it, simply add it to your project:

npm install --save @okta/okta-vue

Configuration

You will need the values from the OIDC client that you created in the previous step to instantiate the middleware. You will also need to know your Okta Org URL, which you can see on the home page of the Okta Developer console.

In your application's vue-router configuration, import the @okta/okta-vue plugin and pass it your OpenID Connect client information:

// router/index.js

import Auth from '@okta/okta-vue'

Vue.use(Auth, {
  issuer: 'https://{yourOktaDomain}.com/oauth2/default',
  clientId: '{clientId}',
  redirectUri: window.location.origin + '/implicit/callback',
  scopes: ['openid', 'profile', 'email']
})

Use the Callback Handler

In order to handle the redirect back from Okta, you need to capture the token values from the URL. In this example, /implicit/callback is used as the login redirect URI and Auth.handleCallback() component is used to obtain tokens. You can customize the callback route or provide your own component by copying the ImplicitCallback component to your own source tree and modifying as needed.

// router/index.js

const router = new Router({
  ...
  mode: 'history',
  routes: [
    { path: '/implicit/callback', component: Auth.handleCallback() },
    ...
  ]
})

Add a Protected Route

Routes are protected by the authRedirectGuard, which allows access only if isAuthenticated returns true. By default, this method returns true if there is a valid accessToken or valid idToken stored, but this behavior can be customized by defining a custom isAuthenticated function. To protect a route using the guard, add the requiresAuth metadata:

// router/index.js

{
  path: '/protected',
  component: Protected,
  meta: {
    requiresAuth: true
  }
}

Next, overload your router's beforeEach() executer to inject the global navigation guard:

// router/index.js

router.beforeEach(Vue.prototype.$auth.authRedirectGuard())

If a user does not have a valid session, they will be redirected to the Okta Login Page for authentication. Once authenticated, they will be redirected back to your application's protected page.

Show Login and Logout Buttons

In the relevant location in your application, you will want to provide Login and Logout buttons for the user. You can show/hide the correct button by using the $auth.isAuthenticated() method. For example:

// src/App.vue

<template>
  <div id="app">
    <router-link to="/" tag="button" id='home-button'> Home </router-link>
    <button v-if='authenticated' v-on:click='logout' id='logout-button'> Logout </button>
    <button v-else v-on:click='$auth.loginRedirect' id='login-button'> Login </button>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'app',
  data: function () {
    return {
      authenticated: false
    }
  },
  created () {
    this.isAuthenticated()
  },
  watch: {
    // Everytime the route changes, check for auth status
    '$route': 'isAuthenticated'
  },
  methods: {
    async isAuthenticated () {
      this.authenticated = await this.$auth.isAuthenticated()
    },
    async logout () {
      await this.$auth.logout()
      await this.isAuthenticated()

      // Navigate back to home
      this.$router.push({ path: '/' })
    }
  }
}
</script>

Use the Access Token

When your users are authenticated, your Vue application has an access token that was issued by your Okta Authorization server. You can use this token to authenticate requests for resources on your server or API. As a hypothetical example, let's say you have an API that provides messages for a user. You could create a MessageList component that gets the access token and uses it to make an authenticated request to your server.

Here is what the Vue component could look like for this hypothentical example using axios:

// src/components/MessageList.vue

<template>
  <ul v-if="posts && posts.length">
    <li v-for="post in posts" :key='post.title'>
      <p><strong>{{post.title}}</strong></p>
      <p>{{post.body}}</p>
    </li>
  </ul>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      posts: []
    }
  },
  async created () {
    axios.defaults.headers.common['Authorization'] = `Bearer ${await this.$auth.getAccessToken()}`
    try {
      const response = await axios.get(`http://localhost:{serverPort}/api/messages`)
      this.posts = response.data
    } catch (e) {
      console.error(`Errors! ${e}`)
    }
  }
}
</script>

Using a custom login-page

The okta-vue SDK supports the session token redirect flow for custom login pages. For more information, see the basic Okta Sign-in Widget functionality.

To handle the session-token redirect flow, you can create your own navigation guard using the requiresAuth meta param:

// router/index.js

router.beforeEach((to, from, next) {
  if (to.matched.some(record => record.meta.requiresAuth) && !(await Vue.prototype.$auth.isAuthenticated())) {
    // Navigate to custom login page
    next({ path: '/login' })
  } else {
    next()
  }
})

Reference

$auth

$auth is the top-most component of okta-vue. This is where most of the configuration is provided.

Configuration Options

The most commonly used options are shown here. See Configuration Reference for an extended set of supported options.

  • issuer (required): The OpenID Connect issuer

  • clientId (required): The OpenID Connect client_id

  • redirectUri (required): Where the callback is hosted

  • postLogoutRedirectUri | Specify the url where the browser should be redirected after logout. If not sepecified, this will be window.location.origin. This url must be added to the list of Logout redirect URIs on the application's General Settings tab.

  • scopes (optional): Reserved or custom claims to be returned in the tokens. Defaults to ['openid', 'email', 'profile']. For a list of scopes and claims, please see Scope-dependent claims for more information.

  • responseType (optional): Desired token grant types. Default: ['id_token', 'token']. For PKCE flow, this should be left undefined or set to ['code'].

  • pkce (optional) - If true, Authorization Code w/PKCE flow will be used. Defaults to true. If false, Implicit OIDC flow will be used.

  • onAuthRequired (optional): - callback function. Called when authentication is required. If not supplied, okta-vue will redirect directly to Okta for authentication. This is triggered when:

    1. login is called
    2. A route protected by $auth.authRedirectGuard is accessed without authentication
  • onSessionExpired deprecated ((optional) - callback function. Called on token renew failure. :warning: This option will be removed in an upcoming version. When a token renew fails, an "error" event will be fired from the TokenManager and the token will be removed from storage. Presense of a token in storage can be used to determine if a login flow is needed in the isAuthenticated method. Take care when beginning a new login flow that there is not another login flow already in progress. Be careful not to initiate the token renew process in this callback, explicitly with tokenManager.renew() or implicitly with tokenManager.get(), as your app may end up in an infinite loop.

  • isAuthenticated (optional) - callback function. By default, $auth.isAuthenticated will return true if either getIdToken() or getAccessToken() return a value. Setting a isAuthenticated function on the config will skip the default logic and call the supplied function instead. The function should return a Promise and resolve to either true or false. NOTE The default behavior of this callback will be changed in the next major release to resolve to true when both getIdToken() and getAccessToken() return a value. Currently, you can achieve this behavior as shown:

    import Auth from '@okta/okta-vue'
    
    Vue.use(Auth, {
      // ...other configs
      isAuthenticated: async () => {
        const idToken = await Vue.prototype.$auth.getIdToken();
        const accessToken = await Vue.prototype.$auth.getAccessToken();
        return !!(idToken && accessToken);
      }
    })
    
  • tokenManager (optional): An object containing additional properties used to configure the internal token manager. See AuthJS TokenManager for more detailed information.

    • autoRenew (optional): By default, the library will attempt to renew expired tokens. When an expired token is requested by the library, a renewal request is executed to update the token. If you wish to to disable auto renewal of tokens, set autoRenew to false.
    • secure: If true then only "secure" https cookies will be stored. This option will prevent cookies from being stored on an HTTP connection. This option is only relevant if storage is set to cookie, or if the client browser does not support localStorage or sessionStorage, in which case cookie storage will be used.
    • storage (optional): Specify the type of storage for tokens. The types are:
oktaAuth.login(fromUri?, additionalParams?)

Calls onAuthRequired function if it was set on the initial configuration. Otherwise, it will call $auth.loginRedirect. This method accepts a fromUri parameter to push the user to after successful authentication, and an optional additionalParams object.

For more information on additionalParams, see the oktaAuth.loginRedirect method below.

$auth.loginRedirect(fromUri, additionalParams)

Performs a full page redirect to Okta based on the initial configuration. This method accepts a fromUri parameter to push the user to after successful authentication.

The parameter additionalParams is mapped to the AuthJS OpenID Connect Options. This will override any existing configuration. As an example, if you have an Okta sessionToken, you can bypass the full-page redirect by passing in this token. This is recommended when using the Okta Sign-In Widget. Simply pass in a sessionToken into the loginRedirect method follows:

this.$auth.loginRedirect('/profile', {
  sessionToken: /* sessionToken */
})

Note: For information on obtaining a sessionToken using the Okta Sign-In Widget, please see the renderEl() example.

$auth.isAuthenticated

If an isAuthenticated function was set on the configuration object, this method will await and return the result from the provided function. Otherwise, it will return true if there is either a valid access token or an ID token.

$auth.getAccessToken

Returns the access token from storage (if it exists).

$auth.getIdToken

Returns the ID token from storage (if it exists).

$auth.getUser

Returns the result of the OpenID Connect /userinfo endpoint if an access token exists.

$auth.handleAuthentication

Parses the tokens returned as hash fragments in the OAuth 2.0 Redirect URI.

$auth.setFromUri(uri, queryParams)

Store the current URL state before a redirect occurs.

$auth.getFromUri()

Returns the stored URI and query parameters stored by setFromUri

$auth.getTokenManager

Returns the internal TokenManager.

$auth.logout(uri?)

Terminates the user's session in Okta and clears all stored tokens. Accepts an optional uri parameter to push the user to after logout.

Contributing

We welcome contributions to all of our open-source packages. Please see the contribution guide to understand how to structure a contribution.

Installing dependencies for contributions

We use yarn for dependency management when developing this package:

yarn install

Commands

CommandDescription
yarn installInstall all dependencies
yarn startStart the sample app using the SDK
yarn testRun integration tests
yarn lintRun eslint linting tests

Keywords

FAQs

Package last updated on 18 Aug 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc