JWT token cross-domain authentication

JSON Web Token (abbreviation JWT), is the most popular cross-domain authentication solutions.

session login authentication scheme: User information transfer user name and password from the client in the session, the session_id will put the cookie authentication server information storage.

After the visit other pages, taken from the cookie to automatically session_id, then take the authentication information from the session.

The other solution, authentication information, is returned to the client, the client is stored. Next visit other pages, need to pass authentication information back to the server from the client.

JWT is the representative of such programs, the authentication information stored in the client.

                                                      JWT principle

JWT principle is, after server authentication, generate an object in JSON format, sent back to the client, like this below.

{
"User Name": "ADMIN",
"role": "super administrator",
"expiration time": "2019-07-13 00:00:00"
}

Later, the client and server communication time, should send back the JSON object. Server completely rely on the object identified user.

To prevent users from tampering with data, the server when generating the object, will add a signature (more on this later).

Server no longer hold any session data, that is, become a stateless server, and thus relatively easy to achieve expansion.                       

                                               JWT several features

(1) JWT default is not encrypted, but also can be encrypted. After generating the original Token, it can be re-encrypted with a key once.

(2) in the case JWT without encryption, secret data can not be written JWT.

(3) JWT not only can be used for authentication, it can also be used to exchange information. Effective use of JWT, the number of server queries the database can be reduced.

(4) JWT biggest drawback is that, because the server does not save session state, a token can not be abolished in the course of, or change the permissions of the token. That is, once issued JWT, will remain in effect until maturity, unless the server to deploy additional logic.

(5) JWT itself contains authentication information, when disclosed, anyone can get all the permissions of the token. To reduce theft, JWT's validity should be set relatively short. For some of the more important rights, should once again to authenticate the user during use.

(6) In order to reduce fraud, the JWT codes using the HTTP protocol should not be transmitted, to use the HTTPS protocol.

 

Functions to achieve:

Use JWT functional components mounted composer composer require lcobucci / jwt 3.3

                                                              JWT package easy to use:

 

? < PHP 
namespace Tools \ jwt; 

use Lcobucci \ the JWT \ Builder;
 use Lcobucci \ the JWT \ Parser;
 use Lcobucci \ the JWT \ Signer \ Hmac \ Sha256;
 use Lcobucci \ the JWT \ ValidationData; 

/ * * 
 * the Created by PhpStorm. 
 * The User : ASUS 
 * a Date: 2019/4/5 
 * Time: 13:02 
 * / 
class the Token 
{ 
    Private  static  $ _config, = [
         'Audience' => 'http://www.pyg.com', // recipient 
        'id '=>' 3f2g57a92aa ', // unique identification token, there is a simple example of 
        ' sign '=>' pinyougou ' ,// signing key
        'Issuer' => 'http://adminapi.pyg.com', // issuer 
        'The expire' => 3600 * 24 @ validity 
    ]; 

    // generating a token 
    public  static  function getToken to ( $ user_id ) { 

        // Signature Object 
        $ Signer = new new Sha256 ();
         // get the current timestamp 
        $ time = time ();
         // set the issuer, recipient, unique identification, the issue of time, with immediate effect, expiration date, user id, the signature 
        $ token = ( new new Builder ()) -> issuedBy (Self :: $ _config, [ 'Issuer' ])
             -> canOnlyBeUsedBy (Self :: $ _config,['audience'])
            ->identifiedBy(self::$_config['id'], true)
            ->issuedAt($time)
            ->canOnlyBeUsedAfter($time-1)
            ->expiresAt($time + self::$_config['expire'])
            ->with('user_id', $user_id)
            ->sign($signer, self::$_config['sign'])
            ->getToken();
        return (string)$token;
    }

    // Get token request information from the token 
    public  static  function getRequestToken () 
    { 
        IF ( empty ( $ _SERVER [ 'HTTP_AUTHORIZATION is' ])) {
             return  to false ; 
        } 

        $ header = $ _SERVER [' HTTP_AUTHORIZATION is' ];
         $ Method = ' bearer ' ;
         // remove bearer identification token may be present in 
        return  TRIM ( str_ireplace ( $ Method ,' ', $ header )); 
    } 

    // get the user id from the token (the token containing the checksum)
    public  static  function getUserId ( $ token = null ) 
    { 
        $ user_id = null ; 

        $ token = empty ( $ token ) Self :: getRequestToken ():? $ token ; 

        IF (! empty ( $ token )) {
             // order cancellation token determining if the code plus the 
            $ delete_token = Cache ( 'delete_token'):? [];
             if ( the in_array ( $ token , $ delete_token )) {
                 // token has been removed (cancellation)
                return  $ user_id ; 
            } 
            $ token = ( new new Parser ()) -> the parse (( String ) $ token );
             // authentication token 
            $ Data = new new ValidationData ();
             $ Data -> setIssuer (Self :: $ _config, [ ' issuer ']); // authentication issuer 
            $ Data -> setAudience (Self :: $ _config, [' Audience ']); // verify recipient 
            $ Data -> the setId (Self :: $ _config, [' ID ' ]); // authentication token identification 

            IF ! ( $ token -> the validate ( $ Data)) {
                 // token verification fails 
                return  $ user_id ; 
            } 

            // verify signatures 
            $ Signer = new new Sha256 ();
             IF ! ( $ Token -> Verify ( $ Signer , Self :: $ _config, [ 'Sign' ])) {
                 // signature verification fails 
                return  $ user_id ; 
            } 
            // Get token from the user id 
            $ user_id = $ token -> getClaim ( 'user_id' ); 
        } 

        return  $ user_id ; 
    } 
}

 

Guess you like

Origin www.cnblogs.com/shenchanglu/p/11289938.html