How To Get Bearer Token value

Please how do i get the value of the Bearer token passed in the header in YII2

Form the Authorization header value. See https://www.yiiframework.com/doc/guide/2.0/en/runtime-requests#http-headers

thanks @samdark but i cant seem to find the answer from the link you shared

I don’t want to spoil the fun of figuring this out for you so I’ll just give you few tips.

  1. Read and learn the doc’s section Samdark posted.
  2. Header you are looking for is named Authorization (like Samdark mentioned).
  3. The value of this header is like this: Bearer XXX where XXX is the token you are looking for.
  4. There are many ways of getting this value from the header, you could look for example at preg_match function.

This should be more than enough to solve your issue.

@Bizley thanks for you reply, i knew i could get this done using pregmatch i just didnt want to go through that stress, i thought there was a YII method i could call to get it hence the reason i asked. I already did some searches and I found this pattern ‘/^Bearer\s+(.*?)$/’ but i still havent been able to get the value hence the reason i had to ask for help.

Ok, so you have the pattern and know about preg_match. What else is keeping you from resolving the problem? And what is “the stress” here exactly?

@Bizley @samdark

$getHeaders = serialize(Yii::$app->request->headers);

$pattern = ‘/^Bearer\s+(.*?)$/’;

preg_match($pattern, $getHeaders , $matches);

print_r($matches);

this is what i did and i keep getting an empty result, please what am i doing wrong.

  1. You are serializing the headers (why?).
  2. You are not fetching the Authorization header (which you were told to do several times already).

I had to serialize because the second parameter in preg_match has to be a string. Maybe there is something i am not getting, from what i can see in the link shared it doesnt explain how to get the authorization header it only explains how to get all the headers.

Really? So what is this there for?

// returns the Accept header value
$accept = $headers->get('Accept');

Oooh so sorry i wasnt paying close attention, this solves my problem.

I appreciate, thanks a lot.