如何使用 Okta auth 和 Composition API 设置 Vue 应用程序

How to set up a Vue app with Okta auth with Composition API

我正在使用 Okta 设置一个基本的 Vue 身份验证应用程序,基于以下内容:https://github.com/okta/okta-vue。我正在尝试将处理路由和登录重定向的逻辑从选项 API 转换为组合 API。也就是说,App.vue中的login/logout功能,目前是这样写的:

    async login () {
      await this.$auth.signInWithRedirect()
      this.$router.push('/protected')
    },
    async logout () {
      await this.$auth.signOut()
    }

https://github.com/okta/okta-vue#show-login-and-logout-buttons

在组合中可能看起来像这样 API(我认为):

    setup() {
      const router = useRouter()
      
      const login = () => {
        this.$auth.signInWithRedirect()
      }

      const logout = () => {
        this.$auth.signOut()
      }

      return {login, logout, router}
    }

但是,我不确定如何更改 this.$auth.signInWithRedirect()this.$auth.signOut() 以使用组合 API,因为 $auth 似乎不被接受 属性.如何设置 Okta 方法 signInWithRedirect()signOut() 以使用组合 API?我是 Typescript 中 Composition API 和 Vue 的新手。感谢反馈!

下面是剩余的代码:

App.vue

<template>
  <div id="app">
    <button v-if='authState && authState.isAuthenticated' @click='logout' id='logout-button'> Logout </button>
    <button v-else @click='login' id='login-button'> Login </button>
    <router-view/>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'app',
    setup() {
      const router = useRouter()
      
      const login = () => {
        this.$auth.signInWithRedirect()
        router.push('/protected')
      }

      const logout = () => {
        this.$auth.signOut()
      }

      return {login, logout, router}
    }
  
})
</script>

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { OktaAuth } from '@okta/okta-auth-js'
import OktaVue from '@okta/okta-vue'

const oktaAuth = new OktaAuth({
    issuer: 'https://{dev-id}.okta.com/oauth2/default',
    clientId: '{clientId}',
    redirectUri: 'http://localhost:8080/login/callback',
    scopes: ['openid', 'profile', 'email']
  })

  const app = createApp(App)
  app.use(OktaVue, { oktaAuth })
  app.use(router)
  app.mount('#app')

router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { LoginCallback } from '@okta/okta-vue'
import { navigationGuard } from '@okta/okta-vue'
import Protected from '../views/Protected.vue'

const routes: Array<RouteRecordRaw> = [
  { 
    path: '/login/callback', 
    component: LoginCallback 
  },
  {
    path: '/protected',
    name: 'Protected',
    component: Protected,
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach(navigationGuard)

export default router

okta-vue 插件通过 app.use(OktaVue, { oktaAuth }) 配置 global property named $auth (which enables this.$auth usage in the Options API). The property's value is actually the same oktaAuth instance passed into the plugin(即,this.$auth 设置为 oktaAuth)。

在组合 API 中,您可以通过 getCurrentInstance():

访问应用程序的全局属性
// MyComponent.vue
<script lang="ts">
import { getCurrentInstance } from 'vue'
import type { OktaAuth } from '@okta/okta-auth-js'

export default {
  setup() {
    const oktaAuth = getCurrentInstance()!!.appContext.app.config.globalProperties.$auth as OktaAuth
    const login = () => oktaAuth.signInWithRedirect()
    const logout = () => oktaAuth.signOut()
    ⋮
  }
}
</script>

另一种方法是将 oktaAuth 实例移动到共享文件中,需要时可以导入该文件,前提是 oktaAuth$auth 全局实例相同 属性:

// auth.ts
import { OktaAuth } from '@okta/okta-auth-js'

export const oktaAuth = new OktaAuth({
  issuer: `https://${process.env.VUE_APP_OKTA_DOMAIN}/oauth2/default`,
  clientId: `${process.env.VUE_APP_OKTA_CLIENT_ID}`,
  redirectUri: window.location.origin + '/login/callback',
  scopes: ['openid', 'profile', 'email'],
  pkce: true,
})
// main.ts
import OktaVue from '@okta/okta-vue'
import { oktaAuth } from './auth' 

const app = createApp(App)
app.use(OktaVue, { oktaAuth })
⋮
// MyComponent.vue
<script lang="ts">
import { oktaAuth } from './auth' 

export default {
  setup() {
    const login = () => oktaAuth.signInWithRedirect()
    const logout = () => oktaAuth.signOut()
    ⋮
  }
}
</script>

demo