Laravel Passport中间件保护的路由“未经身份验证”问题

时间:2019-06-14 03:18:14

标签: laravel vue.js laravel-5 vuejs2 laravel-passport

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

已更新

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

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,并在其中进行了控制器登录。

控制器

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的前端,我有一个动作呼叫。

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不知道该用户已登录。

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

4 个答案:

答案 0 :(得分:3)

  

还登录的用户只能看到auth用户可以看到的页面。

您怎么样?如果用户可以看到auth用户可以看到的内容,这意味着您正在使用auth令牌发出GET请求吗?如果您使用的是护照,则应将令牌放入“授权”标头中。

axios.defaults.headers.common.Authorization = `Bearer ${token}`;

登录后,使用此标记将令牌放入所有axios请求中,然后就可以使用了。

答案 1 :(得分:3)

在登录组件中使用

methods: {
    login() {
      var instance = axios.create({
        baseURL: "http://tetragolf-api.cubettech.in/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,可与所有资源一起使用。

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

const baseDomain = "http://tetragolf-api.cubettech.in";
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路由。

答案 2 :(得分:2)

如果您只是Consuming your api with javascript,我建议将CreateFreshApiToken中间件添加到您的Web中间件组。

来自文档:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

否则,如其他人所述,请确保在您的请求中包括Authorization标头和Content-Type标头。

答案 3 :(得分:0)

如果您使用Laravel护照通过令牌进行身份验证,请务必确保从客户端调用时为受保护的路由设置身份验证标头(对于任何客户端呼叫)Authorization = Bearer your_token。我使用Laravel Passport和Vue.js制作了一个简单的auth示例,并将其上传到github,请查看on this link。我还建议您阅读this post

您在Laravel中的登录应该像这样

 public function login (Request $request) {

        $user = User::where('email', $request->email)->first();

        if ($user) {

            if (Hash::check($request->password, $user->password)) {
                $token = $user->createToken('Laravel Password Grant Client')->accessToken;
                $response = ['token' => $token];
                return response($response, 200);
            } else {
                $response = "Password missmatch";
                return response($response, 422);
            }

        } else {
            $response = 'User does not exist';
            return response($response, 422);
        }

我的Laravel路线'middleware' => ['json.response'],我用来强制对所有数据进行json

Route::group(['middleware' => ['json.response']], function () {

    Route::middleware('auth:api')->get('/user', function (Request $request) {
        return $request->user();
    });

    // public routes
    Route::post('/login', 'Api\AuthController@login')->name('login.api');
    Route::post('/register', 'Api\AuthController@register')->name('register.api');

    // private routes
    Route::middleware('auth:api')->group(function () {
        Route::get('/logout', 'Api\AuthController@logout')->name('logout');
    });

});

我在guards中的config/auth.php

  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

然后在vue中,您可以使用vuex存储令牌,并使用用户数据重用store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
    strict: debug,
    state: {
        auth: null,
        token: null,
        check:false
    },
    getters: {
        auth: state => state.auth,
        token: state => state.token,
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },

        FETCH_auth_SUCCESS(state, auth) {
            state.auth = auth
            state.check = true
        },

        FETCH_auth_FAILURE(state) {
            state.token = null
        },

        LOGOUT(state) {
            state.auth = null
            state.token = null
            state.check = false
        },

        UPDATE_auth(state, { auth }) {
            state.auth = auth
        }
    },

    actions: {
        saveToken({ commit, dispatch }, { token, remember }) {
            commit('SET_TOKEN', token)

            // if you need store token in cookie (remember me option)
            // Cookies.set('token', token, { expires: remember ? 365 : null })
        },

        async fetchauth({ commit,state }) {
            try {
                axios.defaults.headers.common.Authorization = `Bearer ${state.token}`;
                const { data } = await axios.get('/api/user')

                commit('FETCH_auth_SUCCESS', data)
            } catch (e) {
                //   Cookies.remove('token')
                commit('FETCH_auth_FAILURE')
            }
        },

        updateauth({ commit }, payload) {
            commit('UPDATE_auth', payload)
        },

        async logout({ commit,state }) {
            try {
                axios.defaults.headers.common.Authorization = `Bearer ${state.token}`;
                await axios.get('/api/logout')
            } catch (e) {console.log(e) }

            // Cookies.remove('token')
            commit('LOGOUT')
        },
    }
});

注意 我在每个axios呼叫(受保护的路由)上都设置了令牌axios.defaults.headers.common.Authorization = 'Bearer ${state.token}';,但是您可以在全局范围内执行一次。

vue中的登录方法

 methods: {
    login() {
      console.log("Login");
      axios
        .post("/api/login", {
          email: this.form.email,
          password: this.form.password
        })
        .then(res => {
          // save token to vuex
          this.$store.dispatch("saveToken", { token: res.data.token });
          // get user data, store in vuex
          this.$store.dispatch("fetchauth");
          // redirect
          this.$router.push({path:'/dashboard'});
        })
        .catch(e => {
          console.log(e);
        });
    }
  }

首先通过'auth:api'调用受保护的路由时,需要在标头中设置令牌以访问资源。在axios中是axios.defaults.headers.common.Authorization = 'Bearer ${state.token}';