I want to create RESTful API with Basic Authorization.
How can i do it in php ? how can i get below String and Check authentication on php side via headers ?
Basic Zajkljask34jlksdlfkjds=
I want to create RESTful API with Basic Authorization.
How can i do it in php ? how can i get below String and Check authentication on php side via headers ?
Basic Zajkljask34jlksdlfkjds=
How to read User Name and Password in PHP with Basic Auth. Following code is just and example how you can read basic auth. details and do a autherization.
if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']==$valid_username && $_SERVER['PHP_AUTH_PW']==$valid_password) {
// the user is authenticated and handle the rest api call here
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
} else {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
}
?>
Once authorized you can generate a session key and send it to the client and the client can use that key to call the rest api methods.It is not safe to use basic authentication without SSL. Better if you can use HTTPS. Refer following links to configure basic authentication.
If you are using asp.net web api
http://www.asp.net/web-api/overview/security/basic-authentication
If you are using php i would like to suggest you to use a rest api framework
First you need to create .htaccess file if it's not already in existence. Now, you need to add the following lines:
RewriteEngine On
RewriteRule .* - [e=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Next, add the following lines of code in the PHP file in which you want to parse the information:
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
if (strpos(strtolower($_SERVER['REDIRECT_HTTP_AUTHORIZATION']),'basic')===0)
list($username,$password) = explode(':',base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
}
Here you can see that the username and password are stored in $username and $password variable. Now, you can do whatever you want to do with these values such as checking against database - you can do that by adding the extra logic.