使用Nuxt前端实现Laravel 7 Passport身份验证 [英] Implementing Laravel 7 Passport authentification with Nuxt frontend

查看:64
本文介绍了使用Nuxt前端实现Laravel 7 Passport身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装并配置了Laravel 7.3 Passport,然后重新安装了Nuxt.js并按照此处(与Laravel 5.8.34完美兼容).但是登录时,我在JavaScript控制台中收到了CORS错误消息:

I have installed and configured Laravel 7.3 Passport, then I made a fresh install of Nuxt.js and configure it as explained here (works perfect with Laravel 5.8.34). But when logging in, I get a CORS error message in the javascript console:

通过' http://my-laravel.test/oauth/token '来自来源' http://localhost:3000 '已被CORS政策阻止:对预检请求的响应未通过访问控制检查:否请求中存在"Access-Control-Allow-Origin"标头资源.

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的方法:

Below is how I configured 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 这里.

As you can see in the commented code source, I also tried unsuccessfully with proxy as suggested here and with auth strategy laravel.passport as suggested here.

推荐答案

转到cors.php并确保您具有api/*或laravel sanctum之类的oauth端点.

Go to cors.php and make sure you have oauth endpoint like api/* or laravel sanctum.

您必须先清除配置并缓存,然后才能再次测试

You have to clear config and cache before test again

这篇关于使用Nuxt前端实现Laravel 7 Passport身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆