4

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=

1
  • Basic Authentication Details are sent inside the "Authorization" header of the http request.so you need to read the header and decode the base64 string and get the user name and password and do the Authorization as needed Commented Mar 19, 2016 at 9:55

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

i want to do via Basic Zajkljask34jlksdlfkjds= header only ?
With php you can get the decoded user name and password using $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_USER'] server variables.
i don't get value using $_SERVER['HTTP_AUTHORIZATION'] any hint ?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.