I'm building a very tiny api. In the api im authenticating the request using basic authentication header coming from the request. This is the code upto which I have done
$headers = apache_request_headers() ;
// print_r($headers);
if(isset($headers['Authorization'])){
//$credentials = base64_decode($headers);
print_r($headers['Authorization']);
}
I got the Authorization header as 'Basic YXBpa2V5OmFqZWVzaA==
' Now how will I check if this basic authorization header is valid?
Should I decode the base64 string in the username:password format and check it with the DB or when the username and pass is generated,do I have to store it in a base64 format and compare the request base64 string with the one in DB??
I would like to know what is the standard practice of validating a basic authentication request?
Please suggest some ideas. I am just starting up, please excuse stupidity in questions.
i suggest you to use a api token rather than a user/password combination. with a simple auth token you get two benefits.
Usernames or Passwords may change with the time and if so the user is forced to change all usernames and passwords in his application to get there application back to work. a simple token are constant and don't require any change when the username and password of the user changed.
With basic auth the client need to send there username + password in a unencrypted format. this is not very secure and on the worst case, unauthorized can login into the service backend with username + password from the request. simple token are only valid for api calls.
Generate a simple random token for each API user like Eq57dwypZaFW4f2xxRzFaGjwCYinOn6l13Mvds00P2ZzgdMPTk
and require to send this token on each api request with the request header like
X-API-TOKEN: Eq57dwypZaFW4f2xxRzFaGjwCYinOn6l13Mvds00P2ZzgdMPTk
X-API-CLIENT-ID: 123456
on the server side validate with
<?php
$token = $_SERVER['X-API-TOKEN'];
$userID = $_SERVER['X-API-CLIENT-ID'];
$isValid = $findInDatabase->findToken($userID, $token);
if( $isValid )
{
// process api request
} else {
// invalid token
}
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