POGI
POGI

Reputation: 395

How to send cookie token using axios?

Here's my code for generating token that will response as a cookie.

public function authenticate(Request $request)
{
    // grab credentials from the request

    $credentials = ['email'=>$request->header('email'),'password'=>$request->header('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'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    return response($token)->cookie(
        'token',$token, 60
    );

}

And I'm using axios to process it. Here's my code:

axios({
      method: 'post',
      url: 'http://test.dev/authenticate',
      headers : {
        'email':'[email protected]',
        'password':'secret'
      },
      json:true,
    })
 axios({
      method: 'get',
      url: 'http://test.dev/api/users', 
      json:true,
      withCredentials: true
    });

Now, I'm having a problem on how to send the token to retrieve users list. I've tried to add withCredentials: true but no luck.

I got a response error token_not_provided.

Questions:

  1. How to get the value of the cookie token from response?
  2. How to send the token using axios with Authorization Bearer {token}?

Thank you In Advance.

Upvotes: 2

Views: 3434

Answers (2)

Pitter
Pitter

Reputation: 553

It's necessary to set in your requests header:

withCredentials: true

Then it will allow your, then set the cookie in the 'Authorization' parameter as our friend said in the other answer:

headers: {
Authorization' : 'Bearer ' + CookieToken,
}

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50777

You need to add the token to your axios header:

headers: {
    'Authorization' : 'Bearer ' + token
}

Make sure you store your token once you receive it back from your initial authorization.

Upvotes: 1

Related Questions