Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API how to authentication via Basic Auth?

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=

like image 824
Rohit k Avatar asked Sep 14 '25 19:09

Rohit k


1 Answers

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

like image 155
Deshan Avatar answered Sep 16 '25 08:09

Deshan