首页 > 解决方案 > 使用 Vue 路由器从 Dropbox Oauth 重定向获取访问令牌

问题描述

我正在使用 Dropbox JS SDK 并使用 getAuthenticationUrl 方法实现 OAuth2。此方法需要一个重定向 url,在实现时会打开一个带有 url 的新选项卡:http://localhost:8080/dropbox#access_token=ABCDEFG&token_type=bearer&uid=123456789&account_id=123456789

启动该过程的组件包含:

   created() {
        dropBx = new Dropbox({ fetch: fetch, clientId: this.dropboxAppKey })
        authUrl = dropBx.getAuthenticationUrl('http://localhost:8080/dropbox')
        window.open(`${authUrl}`)
    },

我的路线如下所示:

    {
        path: '/dropbox',
        name: 'DropboxAuthFlow',
        component: () => import('@/views/DropboxAuthFlow.vue'),
        meta: {
            requiresAuth: false,
            dropbox: true,
        },
    },

我正在使用历史模式。我有一个路线守卫,看起来像:

router.beforeEach((to, from, next) => {
    if (to.matched.some(route => route.meta.requiresAuth)) {
        let user = firebase.auth().currentUser
        if (user) {
            next()
        } else {
            next({ name: 'LoginPage' })
        }
    } else if (to.matched.some(route => route.meta.dropbox)) {
        next({ name: 'DropboxAuthFlow' })
    } else {
        next()
    }
})

重定向到新的浏览器选项卡就像我没有登录并且没有按预期显示组件一样。重定向 uri 在开发控制台中被授权: http://localhost:8080/dropbox

所以问题:

1)  How can I get the redirect URL to work with Vue Router 
and display the URL despite the hash info?
2)  How can I parse the access token off the returned URL? 
(will $route.hash work?)

标签: vuejs2vue-routerdropbox-apidropbox-sdk-js

解决方案


所以我找到了一个解决方案......首先更改路由器保护:

router.beforeEach((to, from, next) => {
    if (to.matched.some(route => route.meta.requiresAuth)) {
        let user = firebase.auth().currentUser
        if (user) {
            next()
        } else {
            next({ name: 'LoginPage' })
        }
    } else {
        next()
    }
})

第二...改变路线:

    {
        path: '/dropbox',
        name: 'DropboxAuthFlow',
        component: () => import('@/views/DropboxAuthFlow.vue')
    },

最后更改 URI 重定向页面:

    created() {
        let hash = this.$route.hash
        let token = hash.substring(hash.indexOf('=') + 1, hash.indexOf('&'))
        // pass token via dispatch action to persist data in db
    },

我希望这对面临这个问题的人有所帮助......仍然对其他/更好的解决方案持开放态度。


推荐阅读