Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is basic authentication header validated/checked in a rest api

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.

like image 612
Ajis Avatar asked Sep 12 '14 07:09

Ajis


1 Answers

i suggest you to use a api token rather than a user/password combination. with a simple auth token you get two benefits.

  1. 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.

  2. 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
}
like image 138
ins0 Avatar answered Sep 28 '22 06:09

ins0