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
I don’t want to spoil the fun of figuring this out for you so I’ll just give you few tips.
- Read and learn the doc’s section Samdark posted.
- Header you are looking for is named
Authorization(like Samdark mentioned). - The value of this header is like this:
Bearer XXXwhereXXXis the token you are looking for. - There are many ways of getting this value from the header, you could look for example at
preg_matchfunction.
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?
$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.
- You are serializing the headers (why?).
- 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.
I need an example i try everything but nothing works please help me thanks