Php and basic auth

Basic HTTP Authentication using PHP

In this post, you will learn basic HTTP authentication using the PHP programming language.

HTTP authentication is a process of protecting web resources by providing a username and password when making a request to a web resource. It uses the standard fields in the HTTP header, so there is no need to store the passwords in external files. The web server is responsible for handling the authentication.

HTTP Authentication Process

PHP provides superglobal variables for HTTP authentication. The $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’] contain the username and password provided by the user for authentication. In this, the server responds to the user with an unauthorized 401 response status, and it pop ups a dialog box and asks the user to enter credentials for WWW-Authenticate. The user sends the credentials with an Authenticate header. The server executes this and sends the webpage content to the browser.

Basic HTTP Authentication using PHP

Here, we create a PHP function authenticate(), that contains two sets of username and password in a PHP array. This function accepts the entered username and password as parameters of the user and matches them with the credentials stored in an array. If both username and password match with the stored credentials, then returns TRUE, means the user can access the web page content, otherwise it returns FALSE and again asks for credentials.

?php function authenticate($user, $pass) < $users = array('rocky' =>'@12etp', 'mufasa' => 'Y1907JL'); if (isset($users[$user]) && ($users[$user] === $pass)) < return true; >else < return false; >> ?>

Next, we create a condition that checks whether or not the authentication failed. It sets the HTTP response header to 401 and asks for the credential again.

if (! authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))

In the above code, the HTTP WWW-Authenticate response header defines the authentication method that should be used to gain access to a resource. Here, it is sent along with a 401 unauthorized response. When the browser sees the 401 header, it again pops up a dialog box for username and password. The ‘realm‘ is a security policy domain defined for a web. It may contain any value to identify a secure area. The value in it will be displayed in the dialog box.

Complete Code: Basic HTTP Authentication using PHP

?php function authenticate($user, $pass) < $users = array('rocky' =>'@12etp', 'mufasa' => 'Y1907JL'); if (isset($users[$user]) && ($users[$user] === $pass)) < return true; >else < return false; >> if (! authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) < http_response_code(401); header('WWW-Authenticate: Basic realm="Please Login"'); echo "Please enter a valid username and password."; exit; >echo 'Welcome to this website'; ?>

So, this is how we can secure our web page using simple, basic HTTP authentication. We can also secure login forms, some important messages and much more using this.

Источник

Authentication¶

The Authentication component allows you to to implement authentication methods which can simply update the request with authentication detail (for example by adding an Authorization header). This is useful when you have to send multiple requests to the same endpoint. Using an authentication implementation, these details can be separated from the actual requests.

Installation¶

$ composer require php-http/message

Authentication Methods¶

Authorization header of the HTTP specification

Authorization header of the HTTP specification

Authorization header of the HTTP specification

Array of param-value pairs

Array of authentication instances

Behaviors of the underlying authentication methods

An authentication instance and a matcher callback

Behavior of the underlying authentication method if the matcher callback passes

Add an arbitrary authentication header

Integration with HTTPlug¶

Normally requests must be authenticated “by hand” which is not really convenient.

If you use HTTPlug, you can integrate this component into the client using the authentication plugin .

Examples¶

General usage looks like the following:

$authentication = new AuthenticationMethod(); /** @var Psr\Http\Message\RequestInterface */ $authentication->authenticate($request); 

Basic Auth¶

use Http\Message\Authentication\BasicAuth; $authentication = new BasicAuth('username', 'password'); 

Bearer¶

use Http\Message\Authentication\Bearer; $authentication = new Bearer('token'); 

WSSE¶

use Http\Message\Authentication\Wsse; $authentication = new Wsse('username', 'password'); 

For better security, also pass the 3rd optional parameter to use a better hashing algorithm than sha1 , e.g.

use Http\Message\Authentication\Wsse; $authentication = new Wsse('username', 'password', 'sha512'); 

Query Params¶

use Http\Message\Authentication\QueryParam; $authentication = new QueryParam([ 'access_token' => '9zh987g86fg87gh978hg9g79', ]); 

Using query parameters for authentication is not safe. Only use it when this is the only authentication method offered by a third party application.

Chain¶

The idea behind this authentication method is that in some cases you might need to authenticate the request with multiple methods.

For example it’s a common practice to protect development APIs with Basic Auth and the regular token authentication as well to protect the API from unnecessary processing:

use Http\Message\Authentication\Chain; $authenticationChain = [ new AuthenticationMethod1(), new AuthenticationMethod2(), ]; $authentication = new Chain($authenticationChain); 

Matching¶

With this authentication method you can conditionally add authentication details to your request by passing a callable to it. When a request is passed, the callable is called and used as a boolean value in order to decide whether the request should be authenticated or not. It also accepts an authentication method instance which does the actual authentication when the condition is fulfilled.

For example a common use case is to authenticate requests sent to certain paths:

use Http\Message\Authentication\Matching; use Psr\Http\Message\RequestInterface; $authentication = new Matching( new AuthenticationMethod1(), function (RequestInterface $request)  $path = $request->getUri()->getPath(); return 0 === strpos($path, '/api'); > ); 

In order to ease creating matchers for URLs/paths, there is a static factory method for this purpose: createUrlMatcher The first argument is an authentication method, the second is a regular expression to match against the URL:

use Http\Message\Authentication\Matching; $authentication = Matching::createUrlMatcher(new AuthenticationMethod(), '\/api'); 

With this authentication method you can add arbitrary headers.

In the following example, we are setting a X-AUTH-TOKEN header with it’s value:

use Http\Message\Authentication\Header; $authentication = new Header('X-AUTH-TOKEN', '9zh987g86fg87gh978hg9g79'); 

Implement Your Own¶

Implementing an authentication method is easy: only one method needs to be implemented:

use Http\Message\Authentication; use Psr\Http\Message\RequestInterface; class MyAuth implements Authentication  public function authenticate(RequestInterface $request)  // do something with the request // keep in mind that the request is immutable - return the updated // version of the request with the authentication information added // to it. return $request; > > 

© Copyright 2015, The PHP-HTTP Team. Revision 749bb3a1 .

Источник

HTTP Basic Authentication with PHP

There many ways of performing authentication over the web. You can use a token and pass it as a special header. This is commonly done with API tokens. You can also use a cookie to store a session token. This is common for webservers that have a database session in the backend.

One simple method is to use HTTP Basic Access Authentication. This involves adding a header that contains your username and password. The proper format for the header is:

Authorization: Basic XXXXXX 

Where XXXXXX is your credentials in the form of username:password with base64 encoding.

PHP automatically decodes and splits the username and password into special named constants:

  • PHP_AUTH_USER with the username as a plain-text string
  • PHP_AUTH_PW with the password as a plain-text string

We will look at how to restrict a page using HTTP basic authentication in PHP.

Example of HTTP Basic Auth

Access denied. You did not enter a password.

'; exit; // Be safe and ensure no other content is returned. > // If we get here, username was provided. Check password. if ($_SERVER['PHP_AUTH_PW'] == '$ecret') < echo '

Access granted. You know the password!

'; > else < echo '

Access denied! You do not know the password.

'; >

Hashing passwords

Really, you should never be storing passwords in plain-text. If you are storing user account information in a file or a database, the password should be hashed with a salt and each user should have a unique salt. The salt will be useful if the database is ever compromised by making it harder to crack the passwords by reducing the effectiveness of rainbow tables. It will also reduce the amount of identical hashes caused by people using the same password.

PHP’s password_hash() can take care of the hashing and the salt generation. Here is a quick example, but you can read more about Safe Password Hashing.

You use password_hash() to generate the hash that you want to store in your database or password file. This will include the salt.

When a user attempts to authenticate and they provide a password, you use crypt() and pass it the user-supplied password along with your stored hash and then compare that to the stored hash. See the example below.

Testing with curl

If you want to test, an easy way to send an HTTP request with a properly formatted header is with curl . It has a convenient —user option you can set like this:

curl --user my_username:my_password http://localhost:8000/ 

Conclusion

After reading this, you should understand how to restrict a page using simple HTTP basic authentication in PHP.

References

Источник

Читайте также:  Import requests exceptions python
Оцените статью