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

4

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

3
  • It's really helpful for me.Thank you so much ZealousWeb. Commented Feb 8, 2021 at 4:09
  • Could you please upvote? Commented 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 Commented Feb 8, 2021 at 7:10
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 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.