本文介绍了Laravel Passport中间件保护的路由“未经身份验证"问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel Passport进行身份验证,因此我将路由放入中间件保护中.

I am using Laravel Passport for the authentication, so I put my routes into middleware protection.

为了清楚起见,我也添加了UsersController.

To make it clear, I am adding UsersController too.

public function getUser()
{
    $users = Auth::user();
    return response()->json($users);
}

//

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function () {
    /* users */
    Route::get('/users', 'Api\UsersController@getUser');

    /* fetch */
    Route::get('/articles', 'Api\ArticlesController@allArticles');
    Route::get('/article/{id}', 'Api\ArticlesController@singleArticle');
});

当然,我需要登录,否则看不到受保护的路由.我做了一个AuthController,里面有一个控制器登录功能.

Of course, I need to log in, or I can't see the protected routes. I made an AuthController and inside that a controller login function.

控制器

public function login(Request $request)
{
    $http = new \GuzzleHttp\Client;
    try {
        $response = $http->post(config('services.passport.login_endpoint'), [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => config('services.passport.client_id'),
                'client_secret' => config('services.passport.client_secret'),
                'username' => $request->email,
                'password' => $request->password,
            ]
        ]);
        return $response->getBody();
    } catch (\GuzzleHttp\Exception\BadResponseException $e) {
        if ($e->getCode() === 400) {
            return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
        }

        if ($e->getCode() === 401) {
            return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
        }

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

在vuex的前端,我有一个动作呼叫.

In the frontend in my vuex, I have an action call.

retrieveToken(context, credentials){
    return new Promise((resolve, reject) => {
            axios.post("api/v1/login", {
                email: credentials.username,
                password: credentials.password,
            })
            .then(response => {
                const token = response.data.access_token;
                localStorage.setItem("access_token", token);
                context.commit("retrieveToken", token);
                resolve(resolve);
            })
            .catch(error => {
                console.log(error);
                reject(response);
            })
    })
},

一切都很好.我存储令牌并将其用于登录,然后将其删除以注销.但是在后端,缺少了一些东西.因为即使登录,我仍然看不到受保护的路由. Laravel的Auth不知道该用户已登录.

Everything is fine. I store the token and use that for the login and delete it for the log out. But at the backend, something is missing. Because even if login, I still can't see the protected routes. Laravel's Auth doesn't know that user logged in.

我应该在哪里将令牌放入标头?在控制器内部还是登录方式?还是我需要做其他事情?

Where should I put the token into the header? Inside the controller or login method? Or do I need to do something else?

推荐答案

在登录组件中使用

methods: {
    login() {
      var instance = axios.create({
        baseURL: "http://apiendpoint.com/api/"
      });

      instance
        .post("/admin-login", {
          email: this.username,
          password: this.password,
          device_type: "Web",
          device_token: "Web"
        })
        .then(response => {
          // console.log(response);

          localStorage.setItem("token", response.data.data.token);
          this.$router.push("/");
        })
        .catch(error => {
          console.log(error);
        });
    }
  },

然后在文件中将axios配置定义为Repository.js,可将其与所有资源一起使用.

Then define the axios configuration in a file as Repository.js which can be used with all resources.

/******************** Repository js ****************/
import axios from "axios";
import router from "./router";

const baseDomain = "http://apiendpoint.com/api/";
const baseURL = `${baseDomain}/api`;

const api = axios.create({
    baseURL, // headers: {
    //  'Authorization': 'Bearer ' + localStorage.getItem('api_token')
    // },
    validateStatus: function(status) {
        if (status == 401) {
            router.push("/login");
        } else {
            return status;
        }
    }
});
api.interceptors.request.use(
    function(config) {
        const token = localStorage.getItem("token");

        if (token == null) {
            console.log("Token Is empty");
            console.log("Redirecting to Login");
            router.push({ name: "login" });
        }

        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    function(response) {
        return response;
        console.log(response);
    },
    function(error) {
        console.log(error);

        return error;
    }
);
// Add a response interceptor
api.interceptors.response.use(
    function(response) {
        // Do something with response data
        return response;
    },
    function(error) {
        // Do something with response error
        console.log("Error Found");

        return Promise.reject(error);
    }
);
export default api;

并在路由器中定义所有vue路由.

And define all vue routes in Router.

这篇关于Laravel Passport中间件保护的路由“未经身份验证"问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:23