Best practice for sending authorization via HTTP header

Asked

Viewed 388 times

1

I am developing a Rest api, I need to pass some data on all the requests that are basically the required authorization. The data are: Token, unit and an id. What better way to pass this via header. I tried something like this:

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

However I cannot recover this data separately in php.

1 answer

1


I tried something like this: Authorization: MinhaAuth Token="0PN5J17HBGZHT7JJ3X82", unidade="aaa". However I cannot recover this data separately in php.

Answering the above question...

Server Configuration

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

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

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

fastcgi_pass_header Authorization;

Capturing in PHP

You can capture the elements with the function preg_match. 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 the Regex

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

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

unidade="(?<Unidade>.*)" Here it will capture all the value that is between " (quotes) 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']

  • It worked thanks, however it ta returning repeated the token and etc one with the name 'token" same and another as '0'

  • 1

    @And that’s just the way preg_match works. It’s not a mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.