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
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
- It's really helpful for me.Thank you so much ZealousWeb.Ronak Bhatti– Ronak Bhatti2021-02-08 04:09:42 +00:00Commented Feb 8, 2021 at 4:09
- Could you please upvote?ZealousWeb– ZealousWeb2021-02-08 07:03:47 +00:00Commented 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 displayedRonak Bhatti– Ronak Bhatti2021-02-08 07:10:13 +00:00Commented Feb 8, 2021 at 7:10
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