JWT (JSON Web Token) Multi-site Single sign-on, discard session

Source: Internet
Author: User
Tags base64 php class codeigniter

The sharing of login information between multiple sites, one solution is based on the Cookie-session login authentication method, which is more complex across domains.

Another alternative is to use the method of algorithm-based authentication, JWT (JSON Web token).

Reference Links:

    • Http://www.tuicool.com/articles/IRJnaa
    • Https://coderwall.com/p/8wrxfw/goodbye-php-sessions-hello-json-web-tokens
I. Concepts and definitions 1, what is JWT? JSON Web token (JWT) is a JSON-based open standard (RFC 7519) that executes in order to pass claims across a network application environment. The token is designed to be compact and secure, and is ideal for single sign-on (SSO) scenarios in distributed sites. JWT is typically used to pass authenticated user identities between identity providers and service providers to obtain resources from a resource server, or to add additional declarative information that is necessary for other business logic, and JWT can be used either directly for authentication or to be encrypted. 2. Background and significance

Speaking of JWT, we should compare token-based authentication with traditional session authentication methods.

2.1, the traditional session certification

We know that the HTTP protocol itself is a stateless protocol, which means that if a user provides a user name and password to our application for user authentication, then the next request, the user will also have to authenticate the user again, because according to the HTTP protocol, we do not know which user is the request,

So in order for our app to recognize which user is making the request, we can only store a copy of the user's login information in the server, which will be passed to the browser in response, telling it to be saved as a cookie so that the next request is sent to our app, This allows our application to identify which user the request is from ,

This is the traditional session-based authentication. But this session-based authentication makes it hard to extend the application itself,

With the increase of different client users, the independent server can not host more users, and this time based on the session authentication application problems will be exposed. Based on the problems revealed by the session certification:

Session: After each user through our application certification, our application will be on the server to make a record to facilitate the identification of the next request, usually the session is stored in memory, and with the increase in authentication users, the service side of the overhead will be significantly increased.

Extensibility: After the user authentication, the service side does the authentication record, if the authentication record is kept in memory, this means that the user next request must also request on this server, in order to get the authorized resources, so that in the distributed application, the corresponding limit the ability of the load balancer. This also means limiting the application's ability to scale.

CSRF: Because cookies are based on user identification, if the cookie is intercepted, the user will be vulnerable to cross-site request forgery attacks.

2.2. Token-based authentication mechanism

Token-based authentication mechanism is similar to the HTTP protocol is stateless, it does not need to keep the user's authentication information or session information on the server. This means that applications based on the token authentication mechanism do not need to consider which server the user is logged on to, which facilitates the extension of the application.

This is the process:

    1. The user uses the user name password to request the server
    2. The server verifies the user's information and verifies that the server sends a token to the user
    3. The client stores tokens and comes with this token value on each request
    4. The server validates the token value and returns the data that the user wants to access

This token must be passed to the server on each request, it should be stored in the request header, and the server will support Cors (cross-origin resource sharing) policy, generally we can do this on the server access-control-allow-origin: *.

3, the composition of JWT

What does a JWT look like? JWT is composed of three pieces of information, the three pieces of information text with the. Link together to form the JWT string. Just like this:
Eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9. eyjzdwiioiixmjm0nty3odkwiiwibmftzsi6ikpvag4grg9liiwiywrtaw4ionrydwv9. Tjva95orm7e2cbab30rmhrhdcefxjoyzgefonfh7hgq

The first part we call it the head (header), the second part we call it load (payload, similar to the goods carried on the aircraft), the third part is the visa (signature).

3.1. Header

JWT's head carries two pieces of information:

Claim type, here is JWT
An algorithm that declares encryption is usually used directly with the HMAC SHA256

The full head is like this JSON:

' Typ ': ' JWT ',
' ALG ': ' HS256 '
The head is then base64 encrypted (the encryption can be decrypted symmetrically), forming the first part: eyj0exaioijkv1qilcjhbgcioijiuzi1nij9

3.2, Playload

Loads are places where effective information is stored. The name is like a particular item on a plane that contains three pieces of information.

    • Declaration of registration in the standard
    • Public statements
    • Private claims

Declarations registered in the standard (recommended but not mandatory):

    • ISS:JWT issued by
    • SUB:JWT-oriented users
    • AUD: The party receiving the JWT
    • EXP:JWT expiration time must be greater than the time of issue
    • NBF: Defines the time before which the JWT is not available.
    • IAT:JWT Time of issue
    • JTI:JWT's unique identity is used primarily as a one-time token to avoid replay attacks.

Public statements:

    • Public declarations can add any information, generally add information about the user or other necessary information for business needs. However, it is not recommended to add sensitive information because the part is decrypted on the client.

Private statement:

    • A private statement is a statement that is defined by both the provider and the consumer, and is generally not recommended for storing sensitive information, because Base64 is symmetric and decrypted, meaning that the part of the information can be classified as plaintext information.

Define a payload:

"Sub": "1234567890",
"Name": "John Doe",
"Admin": true
It is then base64 encrypted to get the second part of the JWT: eyjzdwiioiixmjm0nty3odkwiiwibmftzsi6ikpvag4grg9liiwiywrtaw4ionrydwv9

3.3, Signature

The third part of JWT is a visa information, which consists of three parts:

    • Header (after Base64)
    • Payload (after Base64)
    • Secret

This section requires Base64 encrypted headers and Base64 after the encrypted payload is used. A string of connections, and then add salt secret combination encryption by the encryption declared in the header, which then forms the third part of the JWT.

var encodedstring = Base64urlencode (header) + '. ' + base64urlencode (payload);

var signature = HMACSHA256 (encodedstring, ' secret '); Tjva95orm7e2cbab30rmhrhdcefxjoyzgefonfh7hgq

Use these three parts. Connect to a complete string that forms the final JWT:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBa B30rmhrhdcefxjoyzgefonfh7hgq

Note: The secret is stored on the server side, and the JWT sign-up is also on the server side, secret is used for the signing of JWT and JWT verification, so it is your service side of the private key, in any scenario should not be revealed. Once the client learns about this secret, it means that the client can self-issue the JWT.

Second, JWT assembly process

JWT (JSON Web Token) is a very lightweight specification that allows us to use JWT to deliver secure and reliable information between users and servers. A JWT is actually a string that consists of three parts, the head, the payload, and the signature.

1. Load (Payload)

We will first describe the user-authenticated operation as a JSON object. Some additional information was added to help understand the JWT for future servers receiving this JWT.
"Sub": "1",
"ISS": "Http://localhost:8000/auth/login",
"IAT": 1451888119,
"Exp": 1454516119,
"NBF": 1451888119,
"JTI": "37c107e4609ddbcc9c096ea5ee76c667"
The first 6 fields are defined by the JWT standard.

    • Sub: The user to which the JWT is intended
    • ISS: The issuer of the JWT
    • IAT (issued at): When to issue tokens
    • EXP (expires): When does token expire
    • NBF (not before): Token cannot be received before this time is processed
    • JTI:JWT ID provides a unique identifier for Web token

The above JSON object is Base64 encoded to get the following string:

Eyjzdwiioiixiiwiaxnzijoiahr0cdpcl1wvbg9jywxob3n0ojgwmdfcl2f1dghcl2xvz2luiiwiawf0ijoxnduxodg4mte5lcjlehaioje0ntq1mtyxmtksi M5izii6mtq1mtg4odexoswianrpijoimzdjmta3ztq2mdlkzgjjyzljmdk2zwe1zwu3nmm2njcifq
This string we call it the payload (load) of the JWT.

If you use node. js, you can use the node. js package Base64url to get this string:

var Base64url = require (' Base64url ')
var Header = {
"From_user": "B",
"Target_user": "A"
Console.log (Base64url (json.stringify (header)))

Note:Base64 is an encoding, that is, it can be translated back to the original appearance. It is not a cryptographic process.

2. Head (header)

JWT also requires a head, which is used to describe the most basic information about the JWT, such as its type and the algorithm used to sign it. This can also be represented as a JSON object:

"Typ": "JWT",
"ALG": "HS256"
Here we show that this is a JWT, and the signature algorithm we use (which is mentioned later) is the HS256 algorithm.
It also has to be Base64 encoded, and then the string becomes the header of the JWT (head):

3. Signature (signature)

Use a period for the two encoded strings above. Connected together (head in front), formed:

Finally, we encrypt the string above the concatenation with the HS256 algorithm. At the time of encryption, we also need to provide a key (secret):

Base64urlencode (header) + "." +
Base64urlencode (payload),
So we can get our encrypted content: WYOQ95RJAYQ2FF3AJ8EVCSAUMEP0KUQCCJDENNFNAT4
This part is also called signature.

4. Assembly

Finally, this part of the signature is also stitched behind the signed string, and we get the full JWT:
eyj0exaioijkv1qilcjhbgcioijiuzi1nij9. eyjzdwiioiixiiwiaxnzijoiahr0cdpcl1wvbg9jywx
Exoswianrpijoimzdjmta3ztq2mdlkzgjjyzljmdk2zwe1zwu3nmm2njcifq. WYOQ95RJAYQ2FF3AJ8EVCSAUMEP0KUQC

Third, appendix

Goodbye PHP Sessions, Hello JSON Web Tokens
REST API ' s is meant to be stateless. What, means is, each request from a client should include all the information needed to process the request. In other words, if is writing a REST API in PHP and you should not is using $_session to store data about the client ' s session. But then how does we remember if a client is logged on or anything else about the their state? The only possibility is, the client must be tasked with keeping track of the state. How could this ever is done securely? The client can ' t be trusted!

Enter the JSON Web tokens. A JSON web token is a bit of JSON, perhaps something that looks like this:

"User": "Alice",
"Email": "[email protected]"
Of course, we can ' t just give this to a client and the them give it back to us without some sort of assurance the IT has N ' t been tampered with. After all, what if they edit the token as follows:

"User": "Administrator",
"Email": "[email protected]"
The solution to this is the JSON Web tokens was signed by the server. If the client tampers with the data then the token ' s signature would no longer match and an error can be raised.

The JWT PHP class makes. For example, to create a token after the client successfully logs in, the following code could is used:

$token = Array ();
$token [' id '] = $id;
Echo Jwt::encode ($token, ' Secret_server_key ');
And then on later API calls the token can be retrieved and verified by this code:

$token = JWT::d ecode ($_post[' token '), ' Secret_server_key ');
Echo $token->id;
If the token has been tampered with then $token'll be empty there'll is not being an ID available. The JWT class makes sure, invalid data is never made available. If the token is tampered with, it'll be unusable. Pretty Simple stuff!

You can get the PHP JWT class as a single file From:https://github.com/rmcdaniel/angular-codeigniter-seed/blob/master/api /application/helpers/jwt_helper.php

As it is used by the AngularJS CodeIgniter Seed project:


Or the original code from:


Written by Richard McDaniel

JWT (JSON Web Token) Multi-site Single sign-on, discard session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.