如何在 Laravel 5.8 中附加授权标头

Posted

技术标签:

【中文标题】如何在 Laravel 5.8 中附加授权标头【英文标题】:How to append Authorization Header in Laravel 5.8 【发布时间】:2019-09-07 17:24:25 【问题描述】:

我想在我的 Laravel 中附加 Authorization: Bearer yourtokenhere。如果在 邮递员我将授权放在标题选项卡上并通过编写Bearer token 手动给出令牌值,这样我就可以保护特定的路线,但是如何在 Laravel 源代码中做到这一点?我应该在我的控制器中做什么,或者我应该在中间件或内核或其他地方添加另一种方法? 这是因为每次访问受jwt.auth middleware 保护的路由时,我都会得到"error":"token_not_provided"

这是我的受保护路线,给我"error":"token_not_provided"

Route::group(['middleware' => ['jwt.auth']], function()
    Route::get('/dashboard', 'AppController@dashboard');
);

这是我在 AuthController 中的登录方法:

  public function signin(Request $request)
  
    $this->validate($request, [
      'username' => 'required',
      'password' => 'required'
    ]);
    // grab credentials from the request
    $credentials = $request->only('username', 'password');
    try 
        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) 
            return response()->json([
              'error' => 'Invalid Credentials, username and password dismatches. Or username may not registered.',
              'status' => '401'
            ], 401);
        
     catch (JWTException $e) 
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    

    return response()->json([
      'user_id' => $request->user()->id,
      'token'   => $token
    ]);
  

【问题讨论】:

【参考方案1】:

你可以这样设置

$request = Request::create(route('abc', 'GET'); $request->headers->set('X-Authorization', 'xxxxx');

有关更多信息,您可以关注此 *** 答案 How to set headers for forwarded request

如果您使用 jwt,您甚至可以在 url 中传递您的令牌 喜欢www.example.com/post?token=kjdhfkjsffghrueih

就像你说的那样,你需要在AuthAcontroller 中使用它,然后你必须在客户端设置它。 首先将该令牌存储在本地存储中并将该令牌设置为从本地存储中的http调用(我猜是通过ajax或axios),然后将请求发送到laravel。

要在 ajax 调用中访问,您可以使用以下代码

headerParams = 'Authorization':'bearer t-7614f875-8423-4f20-a674-d7cf3096290e'; //token form localstorage

然后像ajax一样使用它

type: 'get', url: 'https://api.sandbox.slcedu.org/api/rest/v1/students/test1', headers: headerParams,

或者如果你使用 axios,你可以设置这个

axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('SecurityKey');

【讨论】:

我应该在哪里设置这个?在我登录 AuthController 还是在哪里? 为什么需要在 authcontroller 中设置它应该在客户端设置,如果您从 android 使用此路由,然后从 android 设置 ti,或者如果您使用一些 ajax 调用,如 axios 或 @ 987654329@那里可以设置 感谢它通过尝试这个工作:www.example.com/post?token=kjdhfkjsffghrueih,但我怎样才能让每条访问路线总是自动放置?token=[myToken] 如果使用 Ajax,我应该将令牌存储到 session/cookie 还是 localStorage 中?因为在我的上一个项目(MEAN Stack)中,我确实将令牌和用户数据保存在 localStorage 中。 @Manchesteriyah 抱歉回复晚了,但是是的,您是对的,您必须在本地存储中设置令牌,名称为“securityKey”或AccessKey 或任何适合您的名称。你可以像headerParams = 'Authorization':'bearer t-7614f875-8423-4f20-a674-d7cf3096290e';一样在ajax中设置你的标题,然后在像type: 'get',headers: headerParams,这样的ajax中使用该变量

以上是关于如何在 Laravel 5.8 中附加授权标头的主要内容,如果未能解决你的问题,请参考以下文章