Search code examples
phplaraveltokenjwt

How to append Authorization Header in Laravel 5.8


I'd like to append Authorization: Bearer {yourtokenhere} in my Laravel. If in Postman I put the Authorization on Headers Tab and give token value manually by writing Bearer {token} so I can protect specific route, but how to do this in Laravel source code? What should I do in my controller or should I add another method on Middleware or Kernel or somewhere else? This is because I got {"error":"token_not_provided"} every accessing a route that protected with jwt.auth middleware.

This is my protected route which is give me {"error":"token_not_provided"}:

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

And this is my signin method inside 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
    ]);
  }

Solution

  • You can set this like

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

    for more info you can follow this stackoverflow answer How to set headers for forwarded request

    if you using jwt you can even pass your token in url too like www.example.com/post?token=kjdhfkjsffghrueih

    and like you said , you need this in AuthAcontroller then you have to set this in client side. first store that token in localstorage and set that token to http call(via ajax or axios i guess) from localstorage and then send request to laravel.

    for accessing in ajax call you can use below code

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

    and then use it in ajax like

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

    or if you using axios you can set this by

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