首页 > 解决方案 > 使用 Nuxt 前端实现 Laravel 7 Passport 身份验证

问题描述

我已经安装并配置了 Laravel 7.3 Passport,然后我重新安装了 Nuxt.js 并按照此处的说明进行配置(与 Laravel 5.8.34 完美配合)。但是登录时,我在 javascript 控制台中收到一条 CORS 错误消息:

从源“ http://localhost:3000 ”访问“ http://my-laravel.test/oauth/token ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。

下面是我配置 Nuxt.js 的方式:

pages/index.vue

<template>
  <section class="container">
    <div>
      <strong>Home Page</strong>
      <pre>Both guests and logged in users can access!</pre>
      <nuxt-link to="/login">Login</nuxt-link>
    </div>
  </section>
</template>

pages/login.vue

<template>
  <div class="container">
    <div class="row justify-content-center mt-5">
      <div class="col-md-5">
        <form>
          <div class="form-group">
            <input
              v-model="user.username"
              class="form-control"
              placeholder="Username"
            />
          </div>
          <div class="form-group">
            <input
              v-model="user.password"
              type="password"
              class="form-control"
              placeholder="Password"
            />
          </div>
          <button
            @click.prevent="passwordGrantLogin"
            type="submit"
            class="btn btn-primary btn-block"
          >
            Login with Password Grant
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  middleware: 'guest',
  data() {
    return {
      user: {
        username: '',
        password: ''
      }
    }
  },
  mounted() {},
  methods: {
    async passwordGrantLogin() {
      await this.$auth.loginWith('password_grant', {
        data: {
          grant_type: 'password',
          client_id: process.env.PASSPORT_PASSWORD_GRANT_ID,
          client_secret: process.env.PASSPORT_PASSWORD_GRANT_SECRET,
          scope: '',
          username: this.user.username,
          password: this.user.password
        }
      })
    }
  }
}
</script>

pages/profile.vue

<template>
  <section class="container">
    <div>
      <strong>Strategy</strong>
      <pre>{{ strategy }}</pre>
    </div>
    <div>
      <strong>User</strong>
      <pre>{{ $auth.user }}</pre>
    </div>
    <button @click="logout" class="btn btn-primary">
      Logout
    </button>
  </section>
</template>

<script>
export default {
  middleware: 'auth',
  data() {
    return {
      strategy: this.$auth.$storage.getUniversal('strategy')
    }
  },
  mounted() {},
  methods: {
    async logout() {
      await this.$auth.logout()
    }
  }
}
</script>

nuxt.config.js(部分地)

  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
    '@nuxtjs/pwa',
    '@nuxtjs/auth',
    '@nuxtjs/dotenv',
    'bootstrap-vue/nuxt'
  ],

  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    baseURL: process.env.LARAVEL_ENDPOINT,
    // proxy: true
  },

  // Proxy module configuration
  proxy: {
    '/api': {
      target: process.env.LARAVEL_ENDPOINT,
      pathRewrite: {
        '^/api': '/'
      }
    }
  },

  // Auth module configuration
  auth: {
    // redirect: {
    //   login: '/login',
    //   logout: '/',
    //   callback: '/login',
    //   home: '/profile'
    // },
    // strategies: {
    //   'laravel.passport': {
    //     url: '/',
    //     client_id: process.env.PASSPORT_PASSWORD_GRANT_ID,
    //     client_secret: process.env.PASSPORT_PASSWORD_GRANT_SECRET
    //   }
    // }
    strategies: {
      local: false,
      password_grant: {
        _scheme: 'local',
        endpoints: {
          login: {
            url: '/oauth/token',
            method: 'post',
            propertyName: 'access_token'
          },
          logout: false,
          user: {
            url: 'api/auth/me',
            method: 'get',
            propertyName: 'user'
          }
        }
      }
    }
  },

middleware/guest.js

export default function({ store, redirect }) {
  if (store.state.auth.loggedIn) {
    return redirect('/')
  }
}

.env

LARAVEL_ENDPOINT='http://my-laravel.test/'
PASSPORT_PASSWORD_GRANT_ID=6
PASSPORT_PASSWORD_GRANT_SECRET=p9PMlcO***********GFeNY0v7xvemkP

正如您在注释代码源中看到的那样,我也尝试使用此处建议的代理和此处建议身份laravel.passport验证策略,但均未成功。

标签: laravelauthenticationcorsnuxt.jslaravel-passport

解决方案


转到 cors.php 并确保您有 oauth 端点,例如 api/* 或 laravel sanctum。

您必须在再次测试之前清除配置和缓存


推荐阅读