laravel - 使用 Nuxt 前端实现 Laravel 7 Passport 身份验证

标签 laravel authentication cors nuxt.js laravel-passport

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

Access to XMLHttpRequest at 'http://my-laravel.test/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

下面是我配置 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

如您在注释代码源中所见,我也按照建议尝试使用代理失败 here并按照建议使用身份验证策略 laravel.passport here .

最佳答案

转到 cors.php 并确保你有像 api/* 或 laravel sanctum 这样的 oauth 端点。

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

关于laravel - 使用 Nuxt 前端实现 Laravel 7 Passport 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60979264/

相关文章:

php - 如何使用 Laravel 事件?

php - 将查询参数添加到 Laravel Controller 中的 url

javascript - Laravel5 : Many to many relationship

php - Laravel hasManyThrough 对中间模型有约束

javascript - 如何正确实现 CORS (Access-Control-Allow-Origin)?

java - Standalone.xml 中的 WildFly 10 CORS 设置将被忽略

java - java oauth 2.0 插件编译失败的 Google+ 快速入门

python - 从 DRF 中的 token 字符串获取用户对象?

node.js - 确保我的 API 仅适用于我的前端

amazon-web-services - AWS S3 - ACL 与 CORS 配置与存储桶/对象权限