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
http://www.appelsiini.net/projects/slim-basic-auth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With