What best practice to send authorization via HTTP header [closed]

0

I'm developing an api rest, I need to pass some data on all requisitions that are basically the required authorization. The data is: Token, unit and an id. What would be the best way to pass this via header. I tried something like this:

Authorization: MinhaAuth Token="0PN5J17HBGZHT7JJ3X82", unidade="aaa"

But I can not retrieve this data separately in php.

    
asked by anonymous 01.02.2018 / 14:13

1 answer

1
  

I tried something like this: Authorization: MinhaAuth Token="0PN5J17HBGZHT7JJ3X82", unidade="aaa" . But I can not retrieve this data separately in php.

Answering the above question ...

Server Configuration

In Apache , just add the code below in your .htaccess

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

In Nginx , just add the code below in your configuration file. In my case it stays in /etc/nginx/sites-available

fastcgi_pass_header Authorization;

Capturing in PHP

You can capture the elements with the preg_match function. Just do the following:

<?php

preg_match('/^(?<Auth>\w+).*Token="(?<Token>.*?)".*unidade="(?<Unidade>.*)"/', $_SERVER['HTTP_AUTHORIZATION'], $result);

print_r( $result );
print_r( $_SERVER['HTTP_AUTHORIZATION'] );

Explanation of Regex

  

^(?<Auth>\w+) Here it will get all the alphanumeric value that is at the beginning of Header . In your case MinhaAuth

  

Token="(?<Token>.*?)" Here it will capture all the value that is between "(quotation marks) that comes after Token= . In your case 0PN5J17HBGZHT7JJ3X82

  

unidade="(?<Unidade>.*)" Here it will capture all the value that is between "(quotation marks) that comes after unidade= . In your case aaa

  

?<Token> This part means that it is for him to create an array with the index Token , for example. This way you can capture using $result['Token']

    
01.02.2018 / 14:55