1

I am passing Authorization Bearer Token from postman. i want to fetch that token in magento model.i don't know how to do it ? can anybody help me out ?

2 Answers 2

2

You can use the below code to get the bearer token.

public function getAuthToken(){

    $token = false;

    $headers = []; 
    foreach ($_SERVER as $name => $value) 
    { 
        if (substr($name, 0, 5) == 'HTTP_') 
        { 
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; 
        } 
    }
    $authorizationBearer = '';

    if(isset($headers['Authorization'])) {
        $authorizationBearer = $headers['Authorization'];
    } else if(isset($headers['authorization'])) {
        $authorizationBearer = $headers['authorization'];
    } else {
        $authorizationBearer = "";
    }

    $authorizationBearerArr = explode(' ', $authorizationBearer);
    if(
        isset($authorizationBearerArr[0]) && 
        trim($authorizationBearerArr[0]) == 'Bearer' && 
        isset($authorizationBearerArr[1])
    ){
        $token = $authorizationBearerArr[1];
    }

    return $token;
}

If you still getting any issues let me know.

Thanks

4
  • It's really helpful for me.Thank you so much ZealousWeb. Feb 8, 2021 at 4:09
  • Could you please upvote?
    – ZealousWeb
    Feb 8, 2021 at 7:03
  • My Dear,I tried upvote, "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score." This message displayed Feb 8, 2021 at 7:10
  • Okay, thanks. You can vote after 15 reputations.
    – ZealousWeb
    Feb 8, 2021 at 7:43
2

Declare \Magento\Framework\Webapi\Rest\Request in construct of your class.

Try the following snippet:

/**
 * @var \Magento\Framework\Webapi\Rest\Request
 */
protected $request;

public function __construct(
    \Magento\Framework\Webapi\Rest\Request $request
) {
    $this->request = $request;
}

Then you can do following:

$this->request->getHeader('Authorization'); // To get auth header

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.