简体   繁体   English

使用外部 Laravel 护照 lumen api 进行 Laravel 客户端身份验证

[英]Laravel client authentification with external Laravel passport lumen api

I have been looking online but i can't find any way of doing it.我一直在网上寻找,但我找不到任何方法。 Let me explain, i have an API (Laravel passport on lumen), i tested it with Postman, i get my access token with oauth, everything is fine.让我解释一下,我有一个 API(流明上的 Laravel 护照),我用 Postman 测试了它,我用 oauth 获得了我的访问令牌,一切都很好。 Now i have another Laravel application and i want to know how i can keep all my authentification stuff using the API to login.现在我有另一个 Laravel 应用程序,我想知道如何使用 API 登录我的所有身份验证内容。 I have seen lot of apps that actualy retrieve an api_token and they use 'Auth::user()->where('api_token', $token)'.我见过很多实际检索 api_token 的应用程序,它们使用 'Auth::user()->where('api_token', $token)'。 But i find this wrong because i don't want my client to have access to the database, i want every request to the database to be handled by the API.但我发现这是错误的,因为我不希望我的客户端访问数据库,我希望 API 处理对数据库的每个请求。 Is that possible?那可能吗?

Let say you want to login to a laravel backend app via api.假设您想通过 api 登录到 Laravel 后端应用程序。 make sure you install guzzle.确保你安装了 guzzle。

Route(api): Route::POST('/login', 'AuthController@login')路由(api): Route::POST('/login', 'AuthController@login')

Controller: AuthController.php控制器: AuthController.php

public function login(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required|string',
    ]);

   $http = new \GuzzleHttp\Client;

   try {
    $response = $http->post(config('services.passport.login_endpoint'), [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'your client_id',
            'client_secret' => 'your client_secret',
            'username' => $request->email,
            'password' => $request->password,
            // 'scope' => '',
        ],
    ]);

    return $response->getBody();

    } catch (\GuzzleHttp\Exception\BadResponseException $e) {
        if ($e->getCode() == 401) {
            return response()->json(['message' => 'This action can\'t be perfomed at this time. Please try later.'], $e->getCode());
        } else if ($e->getCode() == 400) {
            return response()->json(['message' => 'These credentials do not match our records.'], $e->getCode());
        }

        return response()->json('Something went wrong on the server. Please try letar.', $e->getCode());
    }
}

In your front-end app for example vuejs, even laravel using vue component.在您的前端应用程序中,例如 vuejs,甚至使用 vue 组件的 laravel。 As you can see, i'm using boostrap-vue but feel free to use the regular html elements如您所见,我使用的是 boostrap-vue,但可以随意使用常规的 html 元素

<template>
  <div>
    <form @submit.prevent="login()">
        <b-form-group label="Email">
          <b-input placeholder="E-Mail" class="ml-1" v-model="form.email" type="email" name="email" :class="{ 'is-invalid': form.errors.has('email') }"/>
          <has-error :form="form" field="email"></has-error>
        </b-form-group>

        <b-form-group>
          <div slot="label" class="d-flex justify-content-between align-items-end">
            <div>Password</div>
            <a href="javascript:void(0)" class="d-block small">Forgot password?</a>
          </div>
          <b-input v-model="form.password" type="password" name="password" :class="{ 'is-invalid': form.errors.has('password') }" />
            <has-error :form="form" field="password"></has-error>
        </b-form-group>

        <div class="d-flex justify-content-between align-items-center m-0">
          <b-check v-model="form.rememberMe" class="m-0">Remember me</b-check>
          <b-btn type="submit" variant="primary">Sign In</b-btn>
        </div>
      </form>
   </div>
  <template>

<script>


export default ({
  name: 'pages-authentication-login-v2',
  metaInfo: {
    title: 'Login'
  },

  state: {
      token: localStorage.getItem('access_token'),
  },

  mutations: {
    login(state, token) {
      state.token = token
    },
  },

  data: () => ({
      form: new Form({
          email: '',
          password: '',
      })
  }),

  methods: {

  login(){
        this.form.post('/api/login')
        .then((response) =>{
            const token = response.data.access_token
            localStorage.setItem('access_token', token)  
            // console.log(response);
            this.$router.push('/dashboard');
        })

        .catch((error)=>{
            this.$toasted.error('Ooops! Something went wrong', {
                icon : "warning",
                theme: "bubble",
                closeOnSwipe: true,
                position: "top-right",
                duration : 5000,
                singleton: true,
            })
        });
  },

  }
})
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM