Design Passport System Using Json Web Token

http://www.cnblogs.com/binyue/p/4812798.html

Using Json Web Token to design the Passport system

1. Token Auth mechanism
Token-based authentication is stateless, and we do not store user information in the server or session.

Compared with the original Cookie+Session method, it is more suitable for user authentication in distributed systems, bypassing the traditional distributed Session consistency and other issues.

The main process of token-based authentication is as follows:

the user sends a request through the username and password; the
program is verified;
the program returns a signed token to the client; the
client stores the token, and each time it is used for each request.

2. Advantages compared to cookie authentication
Support cross-domain and cross-site access:

Cookie does not allow cross-domain access. Partial cross-domain access can be achieved by setting the top-level domain name, but cross-site access is still not supported.
If the Token mechanism is used, User authentication information can be transmitted through HTTP headers, so as to better realize cross-domain and cross-site.

Stateless: The

Token mechanism does not need to store session information on the server side. The Token itself contains the information of the logged-in user, and only needs to store the state information in the client's cookie or local medium;

decoupling: does not need to be bound to a specific authentication scheme . Tokens can be generated anywhere, as long as you can make a token generation call when your API is called;

more suitable for mobile applications:

When the client is a native application, cookies are not supported. Although the current Webview method can solve the cookie problem,

it is obviously much simpler to use the Token authentication mechanism; the

security is stronger:

because you no longer rely on cookies, you There is no need to consider the prevention of CSRF (cross-site request forgery);

standardization is easy to expand:

standardized JSON Web Token (JWT) can be used, which is more convenient for pure front-end development such as system access to Node;

it improves performance compared to session consistency :

Compared with the server saving session consistency information and querying the user's login status, generally speaking, the token verification process (including encryption and decryption) will have lower performance overhead.

Three, JSON Web Token standard design
JWT standard Token has three parts:

header.payload.signature



intermediate portion with three spaced apart points, and use Base64 encoding, the Token generated like this:

ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIkhTMjU2Igp9.ewogImlzcyI6ICJjaGJsb2dzLmNvbSIsCiAiZXhwIjogIjE0NzA3MzAxODIiLAogInVpZCI6ICIxMjM0NWFiY2RlIiwKfQ.9q2eq8sa374ao2uq9607r6qu6

( 1) The

header part of the Header header mainly includes two parts, one is the type of Token, and the other is the algorithm used. For
example, the following type is JWT, and the algorithm used is HS256.

{
"typ": "JWT",
"alg": "HS256"
}

The content of the Header should be encoded in Base64 format, so it becomes like this:
ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIkhTMjU2Igp9

(2) The payload part of

the payload contains the specific content of the Token, this part of the content It can be customized, JWT has standard fields, and other required content can also be added.
Standard fields:
iss: Issuer, Issuer
sub: Subject, Subject
aud: Audience, Audience
exp: Expiration time, Expiration time
nbf: Not before
iat: Issued at, Issue time
jti: JWT ID

This is a typical payload information, including The issuer (website), expiration time and user id:
{
"iss": "chblogs.com",
"exp": "1470730182",
"uid": "12345abcde",
}

This part of the content should also be encoded in Base64, The generated code is similar to the following format:

ewogImlzcyI6ICJjaGJsb2dzLmNvbSIsCiAiZXhwIjogIjE0NzA3MzAxODIiLAogInVpZCI6ICIxMjM0NWFiY2RlIiwKfQ==

(3) Signature part The

signature part is mainly related to the security of the token, and the generation of the Signature depends on the first two parts.
Header and Payload first Base64 encoded by the connection together,

ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIkhTMjU2Igp9.ewogImlzcyI6ICJjaGJsb2dzLmNvbSIsCiAiZXhwIjogIjE0NzA3MzAxODIiLAogInVpZCI6ICIxMjM0NWFiY2RlIiwKfQ


use HmacSHA256 encryption algorithm on the string, this secret key is stored on the server, the front end is not visible, .

1
2 .
3
. 4 .
5 .
6
String STR = "ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIkhTMjU2Igp9."
                + "ewogImlzcyI6ICJjaGJsb2dzLmNvbSIsCiAiZXhwIjogIjE0NzA3MzAxODIiLAogInVpZCI6ICIxMjM0NWFiY2RlIiwKfQ"
        ;
        String key = Coder.initMacKey();
        BigInteger sha = new BigInteger(Coder.encryptHMAC(inputData, key)); System.out.println("After HS256
        encryption - "+sha.toString(32));
  


encrypting key THISSHA:
9q2eq8sa374ao2uq9607r6qu6

then Signature front and two spliced together to give the final token:

ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIkhTMjU2Igp9.ewogImlzcyI6ICJjaGJsb2dzLmNvbSIsCiAiZXhwIjogIjE0NzA3MzAxODIiLAogInVpZCI6ICIxMjM0NWFiY2RlIiwKfQ.9q2eq8sa374ao2uq9607r6qu6

four, the JWT authentication implemented
conventional token stored in or sessionStorage localStorage, on each request will be added to the token In the header of the http request, the

following is a typical token authentication method:

1. When the client logs in, the client uses the account and password to authenticate to the server. After the authentication is passed, the server generates a Token through the key it holds. The Token generally contains invalidation. The duration and the unique identifier of the user, such as the user ID, the server returns the Token to the client;
2. The client saves the Token returned by the server;
3. When the client makes a business request, the Token is placed in the Authorization field of the Head, such as:
Authorization: Bearer Token
4. The server verifies the requested Token. If the Token is not stored in a cookie, the user needs to log out actively, but The set expiration time has not expired.

When the user logs out, the Token that is still invalid can be stored in a cache such as Redis. During verification, check whether the Token exists. If the Token exists in Redis, it means that the user has been logged out; if the Token does not exist, the verification is passed.
5. The server can verify the relevant permissions through the unique user ID obtained from the Token, and assign the user ID to the request parameters, and the business can be processed through the user ID;


another way is to save the token in In the cookie, there is no need to save the value of the token on the server at this time. The cookie can be cleared directly when the user logs out.

This method does not need to store the value of the token on the server. The authentication process is as follows:




5. The security of the JWT standard
( 1) How to access CSRF to attack



CSRF (Cross Site Request Forgery), which means that two tabs are opened in a browser, one of which sends a fake request by stealing the cookie of the other page, because the cookie is automatically sent with the request. sent to the server.

(2) How to ensure the security of the token

The client does not need to hold the key, and the server generates the token through the key;

in JWT, no sensitive data, such as user passwords, should be added to the payload, because the payload There is no encryption, just a Base64 encoding,
After the attacker gets the token, he can obtain the user's sensitive information;



reference material:

Token-based authentication

JSON Web Token - securely transfer information between web applications

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326642925&siteId=291194637