Danny
Danny

Reputation: 4754

Symfony Basic API Http Authentication

Can someone point me in the right direction in regards to making an api use basic http authentication?

I am creating a restful api with symfony but would like to require users to be logged in to get certain data. I would also like many of these methods be dependent on the the username in the authentication process in order to get some of the data (using the username from the credentials to get all of a users friends)

Thanks!

Upvotes: 0

Views: 3643

Answers (1)

Artefacto
Artefacto

Reputation: 97825

Something like this:

function send401() {
    $realm = "Credentials for site xxx";
    header("HTTP/1.0 401 Authorization Required")
    header('WWW-Authenticate: Basic realm="'.$realm.'"');
    die();
}


if (!array_key_exists('PHP_AUTH_USER',$_SERVER) ||
        !array_key_exists('PHP_AUTH_PW',$_SERVER)) {
    send401();
}
else {
    $res = authenticate_user($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
    if (!$res)
        send401();
}

The username is stored in $_SERVER['PHP_AUTH_USER'].

Upvotes: 1

Related Questions