Coder Social home page Coder Social logo

okta-vue's Introduction

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 Okta Auth SDK instance 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 Okta Auth SDK to your components on the Vue prototype
  • Inject reactive authState property to your Vue components

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.

Helpful Links

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 { OktaAuth } from '@okta/okta-auth-js'
import OktaVue from '@okta/okta-vue'

const oktaAuth = new OktaAuth({
  issuer: 'https://{yourOktaDomain}.com/oauth2/default',
  clientId: '{clientId}',
  redirectUri: window.location.origin + '/login/callback',
  scopes: ['openid', 'profile', 'email']
})
Vue.use(OktaVue, { oktaAuth })

Use the LoginCallback Component

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

Note: Make sure you have the /login/callback url (absolute url) added in your Okta App's configuration.

// router/index.js
import { LoginCallback } from '@okta/okta-vue'

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

Add a Protected Route

Route is protected when the requiresAuth metadata is added in the configuration, which allows access only if authState.isAuthenticated is true. By default, authState.isAuthenticated is true if both accessToken and idToken are valid, but this behavior can be customized by defining a custom isAuthenticated function.

// router/index.js

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

If a user does not have a valid session, then a new authorization flow will begin. By default, they will be redirected to the Okta Login Page for authentication. Once authenticated, they will be redirected back to your application's protected page. This logic can be customized by setting an onAuthRequired function on the config object.

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 injected reactive authState property. For example:

// src/App.vue

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

<script>
export default {
  name: 'app',
  methods: {
    async login () {
      await this.$auth.signInWithRedirect()
    },
    async logout () {
      await this.$auth.signOut()
    }
  }
}
</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 ${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 implement a custom login page, set an onAuthRequired callback on the OktaConfig object:

// router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import OktaVue from '@okta/okta-vue'
import { OktaAuth } from '@okta/okta-auth-js'

const oktaAuth = new OktaAuth(/* config */)
const router = new Router({
  mode: 'history',
  routes: [
    // other routes ...
    { path: '/login', component: Login }
  ]
})

Vue.use(Router)
Vue.use(OktaVue, {
  oktaAuth
  onAuthRequired: (oktaAuth) => {
    router.push({ path: '/login' })
  }
})

export default router

Reference

$auth

This SDK works as a Vue Plugin. It provides an instance of the Okta Auth SDK to your components on the Vue prototype. You can access the Okta Auth SDK instance by using this.$auth in your components.

LoginCallback

LoginCallback handles the callback after the redirect to and back from the Okta-hosted login page. By default, it parses the tokens from the uri, stores them, then redirects to /. If a secure route caused the redirect, then the callback redirects to the secured route. For more advanced cases, this component can be copied to your own source tree and modified as needed.

Configuration Options

The base set of configuration options are defined by Okta Auth SDK. The following properties are required:

  • issuer (required): The OpenID Connect issuer
  • clientId (required): The OpenID Connect client_id
  • redirectUri (required): Where the callback is hosted

This SDK accepts all configuration options defined by Okta Auth SDK (see Configuration Reference for the supported options) and adds some additional options:

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 a secure route is accessed without authentication. A common use case for this callback is to redirect users to a custom login route when authentication is required for a SecureRoute.

See Using a custom login-page for the code sample.

Migrating

Each major version release introduces breaking changes, see MIGRATING GUIDE to get your application properly updated.

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

Command Description
yarn install Install all dependencies
yarn start Start the sample app using the SDK
yarn test Run integration tests
yarn lint Run eslint linting tests

okta-vue's People

Contributors

aarongranick-okta avatar bretterer avatar brettritter-okta avatar danab avatar denysoblohin-okta avatar dogeared avatar drcolza avatar feichen-okta avatar gaastonsr avatar ildarabdullin-okta avatar inergy avatar jamesbui-okta avatar jmelberg-okta avatar kitty7756 avatar lboyette-okta avatar manueltanzi-okta avatar mshaaban088 avatar nbarbettini avatar oktauploader-okta avatar oleksandrpravosudko-okta avatar releng-internal-okta avatar robertjd avatar shuowu avatar shuowu-okta avatar swiftone avatar thetonywu avatar vijetmahabaleshwar-okta avatar wayneearl-okta avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.