简体   繁体   English

如何使用带有组合 API 的 Okta auth 设置 Vue 应用程序

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

I am setting up a basic Vue authentication app using Okta, based on the following: https://github.com/okta/okta-vue .我正在使用 Okta 设置一个基本的 Vue 身份验证应用程序,基于以下内容: https://github.com/okta/okta-vue I am attempting to convert the logic that handles routing and signin redirecting from Options API to Composition API.我正在尝试将处理路由和登录重定向的逻辑从选项 API 转换为组合 API。 In other words, the login/logout functionality in App.vue, which is currently written like this:换句话说,App.vue 中的登录/注销功能,目前是这样写的:

    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

Would probably look something like this in Composition API (I think):在作文 API 中可能看起来像这样(我认为):

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

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

      return {login, logout, router}
    }

However, I'm not sure how to change this.$auth.signInWithRedirect() and this.$auth.signOut() to work with Composition API, since $auth doesn't appear to be an accepted property.但是,我不确定如何更改this.$auth.signInWithRedirect()this.$auth.signOut()以使用 Composition API,因为 $auth 似乎不是一个可接受的属性。 How can I set up the Okta methods signInWithRedirect() and signOut() to work with composition API?如何设置 Okta 方法signInWithRedirect()和 signOut( signOut()以使用组合 API? I'm new to Composition API and Vue in Typescript.我是 Typescript 中的组合 API 和 Vue 的新手。 Feedback is appreciated!反馈表示赞赏!

Here is the rest of the code below:这是下面代码的rest:

App.vue应用程序.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 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路由器/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

The okta-vue plugin configures a global property named $auth (which enables this.$auth usage in the Options API). okta-vue插件配置了一个名为$auth全局属性(它允许在选项 API 中使用this.$auth )。 The property's value is actually the same oktaAuth instance passed into the plugin via app.use(OktaVue, { oktaAuth }) (ie, this.$auth is set to oktaAuth ).该属性的值实际上与通过app.use(OktaVue, { oktaAuth })传递给插件的oktaAuth实例相同(即this.$auth设置为oktaAuth )。

In the Composition API, you could access the app's global properties via getCurrentInstance() :在 Composition API 中,您可以通过getCurrentInstance()访问应用程序的全局属性:

// MyComponent.vue
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()
    ⋮
  }
}

Another approach is to move the oktaAuth instance into a shared file that could be imported when needed, given that oktaAuth is the same as the $auth global property:另一种方法是将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
import { oktaAuth } from './auth' 👈

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

demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Vue Okta 应用程序中设置 Okta 登录小部件 - How to set up Okta Signin Widget in Vue Okta app 如何使用反应式方法设置 Vue 3 Composition API (Typescript) todo list app - How to set up Vue 3 Composition API (Typescript) todo list app with reactive method 如何在Vue 3 Composition中设置Pinia getter API - How to set up Pinia getter in Vue 3 Composition API 如何在 Vue 3 Composition API 中设置随机字母生成器 - How to set up a random letter generator in Vue 3 Composition API 如何设置 Vue 3 Composition API (Typescript) 将用户输入的值推送到数组 - How to set up Vue 3 Composition API (Typescript) to push user-inputted value to array 如何使用 Vue apollo 和 composition api 设置身份验证标头? - How to set authentications headers with Vue apollo and composition api? 如何在 Vue 3 脚本设置(Composition API)中设置 DOM 元素高度? - How to set DOM element height in Vue 3 script setup (Composition API)? 如何使用 Composition API 在 Vue 3 应用程序中播放音效 - How to play sound effects in Vue 3 app with Composition API 如何在 Vue 3 + Composition API 应用程序中正确注册组件? - How to properly register a component in a Vue 3 + Composition API app? Vue 3 vue-国际化。 如何在应用程序(.vue 文件)之外使用 $t(t)? 作文 API - Vue 3 vue-i18n. How to use $t(t) outside the app(.vue files)? Composition API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM