使用Nuxt的身份验证模块以Discord OAuth2登录

时间:2020-06-30 23:26:01

标签: javascript oauth-2.0 nuxt.js

我很难使用下面的Discord's OAuth2Nuxt's auth-module设置登录方法,目前,它的工作方式是我转到https://website.com/login,它将我重定向到Discord的OAuth2授权页面,当我对其进行授权时,将重定向到https://website.com/token?code=CODE&state=STATE,然后将code交换为access_tokenrefresh_token,这就是我被困的地方,我尝试使用context.$auth.setUser({ AccessToken: res.data.access_token })设置用户,这也应该将用户的loggedIn状态设置为true,但刷新页面后将恢复该状态。

获得用户的access_token后该怎么办?

nuxt.config.js-身份验证模块配置

auth: {
  strategies: {
    discord: {
      _scheme: 'oauth2',
      authorization_endpoint: 'https://discord.com/api/oauth2/authorize',
      userinfo_endpoint: false,
      scope: ['email', 'identify', 'connections'],
      response_type: 'code',
      redirect_uri: 'https://website.com/token',
      client_id: process.env.CLIENT_ID,
    },
  },
},

/登录

<script>
export default {
  middleware(context) {
    if (context.$auth.loggedIn) context.redirect('/')
  },
  created() {
    if (process.client) this.$auth.loginWith('discord')
  },
}
</script>

/令牌

<script>
const formUrlEncode = (data) => {
  return Object.entries(data)
    .map(([k, v]) => k + '=' + v)
    .join('&')
}
export default {
  async asyncData(context) {
    const data = {
      client_id: context.env.CLIENT_ID,
      client_secret: context.$config.CLIENT_SECRET,
      grant_type: 'authorization_code',
      code: context.query.code,
      redirect_uri: 'https://website.com/token',
      scope: 'identify email connections',
    }

    const res = await context.$axios({
      method: 'post',
      url: 'https://discord.com/api/oauth2/token',
      data: formUrlEncode(data),
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    })
  },
}
</script>

0 个答案:

没有答案