Editor’s note: Today we share the implementation principles and implementation of common authentication schemes for websites as well as their applicable scenarios organized by Lu Shijie to help you make appropriate choices in your business.

background

Speaking of authentication we should be very familiar with, but as a front-end development, authentication process is mostly in the back of the brother side, the purpose of this article is to let you know the common authentication methods and principles.

Cognition: HTTP is a stateless protocol, so each time a client makes a request, the next request cannot know the state data contained in the previous request.

HTTP Auth Authentication

Introduction to the

HTTP provides a general framework for permission control and authentication. The most common HTTP Authentication scheme is HTTP Basic Authentication

Authentication process

Encryption and decryption process

// Authorization encryption process
let email = "[email protected]"
let password = "12345678"
let auth = `${email}:${password}`
const buf = Buffer.from(auth, 'ascii');
console.info(buf.toString('base64')); // cG9zdG1haWxAdGVzdC5jb206MTIzNDU2Nzg=

// Authorization decryption process
const buf = Buffer.from(authorization.split(' ') [1] | |' '),  'base64');
const user = buf.toString('ascii').split(':');
Copy the code

Other HTTP Authentication

The generic HTTP authentication framework is used by several authentication schemes. Different verification schemes will vary in security intensity.

IANA maintains a series of verification schemes. In addition, there are other types of verification schemes provided by virtual hosting services, such as Amazon AWS. Common verification schemes include:

  • Basic (See RFC 7617, Base64 encoding credentials. See below for details.) .
  • Bearer (look at RFC 6750, Bearer of protected resources through OAuth 2.0),
  • Digest (check RFC 7616, only MD5 hash is supported in Firefox, check Bug 472823 for SHA encryption support),
  • HOBA (see RFC 7486 (draft), HTTP Origin-bound authentication, based on digital signatures),
  • Mutual (see draft-IEtf-httpauth-Mutual),
  • Aws4-hmac-sha256 (View AWS Docs)

Cookie + Session

The registration process

Consider: Why salt your password?

Authentication process

The Session storage

The most commonly used Session storage mode is KV storage, such as Redis, which is good in distribution, API support and performance. In addition, there are mysql and file storage.

If the service is distributed and file storage is used, session synchronization may occur between multiple services. Control of incorrect read/write locks in high concurrency.

Session Refresh

In the process we mentioned above, there is no Session refresh. We can’t kick out the user after logging in after an expires time. If the user has been operating for the duration of the Session, then the Expires time should be refreshed.

In Koa’s case, the mechanism for refreshing a Session is simple: Develop a Middleware (through which all requests pass by default) and update Session expires if a Session is valid: Current time + Expiration time.

Optimization:

  1. Frequently updating sessions affects performance. You can update the session expiration time when the session is about to expire.
  2. If a user has been operating for a long time, the same sessionID may be valid for a long time. If related cookies are leaked, there may be a big risk. You can generate a refreshID while generating sessionID. The request server generates a new sessionID with the refreshID after the sessionID expires (this solution requires the front end to determine that the sessionID is invalid and send the request with the refreshID).

Single Device Login

In some cases, only one account can log in from one end. If another end is used, you need to log out the end that you have logged in to. By default, the same account can log in from different ends at the same time.

In this case, a service can be used to save the mapping between the user’s unique id and the session ID. If the user has a different session ID, the login is not allowed or the previous session is kicked out (delete the old session).

Third, JWT

Introduction to the

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, self-contained way to securely transfer information between parties as JSON objects. This information can be authenticated and trusted because it is digitally signed.

JWT composition

The JWT consists of three parts: header, payload, and signature. These three parts are connected by decimal points.

For example, use a cookie named jwt-token to store JWT. For example:

jwt-token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoibHVzaGlqaWUiLCJpYXQiOjE1MzI1OTUyNTUsImV4cCI6MTUzMjU5NTI3MH0.W Z9_poToN9llFFUfkswcpTljRDjF4JfZcmqYS0JcKO8;Copy the code

Three component elements can be obtained by splitting the value of. In order:

  • Header:

    • Value: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
    • Base64 decoding:{"alg": "HS256", "type": "JWT"}
  • Content:

    • Value: eyJuYW1lIjoibHVzaGlqaWUiLCJpYXQiOjE1MzI1OTUyNTUsImV4cCI6MTUzMjU5NTI3MH0
    • Base64 decoding:
      {
        "name": "lushijie"."iat": 1532595255.// Release time
        "exp": 1532595270 // Expiration time
      }
      Copy the code
  • Signature:

    • Value: WZ9_poToN9llFFUfkswcpTljRDjF4JfZcmqYS0JcKO8
    • Decoding:
      const headerEncode = base64Encode(header);
      const payloadEncode = base64Encode(payload);
      let signature = HMACSHA256(headerEncode + '. ' + payloadEncode, 'key');
      Copy the code

Authentication process

Token check

To verify that a JWT is valid, the server computes the signature part of the JWT and compares it with the signature part of the JWT. If the signature part is equal, the JWT is valid.

Token Refresh

In order to reduce the risk of JWT Token disclosure, the validity period is generally set to be shorter. In this case, JWT tokens would expire, and it would be impossible for users to log in frequently to obtain new JWT tokens.

Solution:

JWT Token and Refresh Token can be generated at the same time, where Refresh Roken is valid longer than JWT Token, so that when JWT Token expires, Obtain a new JWT Token and a Refresh Token by using the Refresh Token. The Refresh Token can be used only once.

Fourth, the request

Introduction to the

Sometimes, we log in to a website, but we do not want to register the account of the website, then we can use a third-party account to log in, such as Github, Weibo, wechat, QQ and so on.

Open Authorization (OAuth) is an open standard that allows a user to give third-party applications access to the user’s private resources (such as photos, videos, and contact lists) stored on a website without having to provide a user name and password to third-party applications.

OAuth allows users to provide a token, rather than a username and password, to access the data they store with a particular service provider. Each token grants a specific site (for example, a video editing site) access to a specific resource (for example, just a video in a photo album) for a specific period of time (for example, the next 2 hours). In this way, OAuth lets users authorize third-party sites to access specific information they store with another service provider, but not all of it.

OAuth is a complement to OpenID, but an entirely different service.

— from Wikipedia

Authorization process

Noun explanation:

  • Third-party application: Third-party application is also called client. For example, if you open Zhihu and log in through a Third party, choose Github to log in, Zhihu is the client.
  • Resource Owner: Indicates the Owner of the Resource. In this document, the user is also called the login user.
  • Authorization Server: The Github Authorization server.
  • Resource Server: Github stores user-generated resources. It can be the same server or a different server from the authentication server.

  • A. A website allows users to jump to GitHub and request an authorization code. GitHub asks users to log in, then asks “Zhihu requires xx permission, do you agree?” ;
  • B. If the user agrees, GitHub will redirect to SITE A and send back an authorization code;
  • C. A uses the authorization code to request A token from GitHub;
  • D. GitHub return token;
  • E. A uses A token to request user data from GitHub;

Other Authorization Modes

The Authorization Code mode is the most complete authorization mode with the most rigorous procedures. In addition to the authorization code pattern we mentioned above, there are other authorization patterns:

  1. Implicit Grant Type

Some Web applications are pure front-end applications without a back end. In this case, you can’t use the above method and must store the token in the front end. RFC 6749 provides a second approach that allows tokens to be issued directly to the front end. RFC 6749 also allows you to give your user name and Password directly to an application when you trust it highly. 3. The Client Credentials Grant applies to command line applications with no front end, that is, token requests are made on the command line

See OAuth2.0 for more details on these modes: Four ways

Single sign-on (sso)

Single Sign On (SSO) : Single sign-on (Single sign-on). For example: QQ, I log in once in Qzone, I can access other services of QQ products: QQ mailbox, Tencent news and so on, which can ensure that your account stays logged in state.

Read more:

  • How to Implement Single Sign-on?
  • How can I Log in to the Intranet by Scanning codes on mobile phones?

Fifth, summarize and compare

No best, only the most appropriate!!

  • HTTP Auth Authentication:
    • Summary: The generic HTTP authentication framework uses multiple authentication schemes. Different verification schemes will vary in security intensity. HTTP Auth Authentication is the most commonly used HTTP Authentication scheme. To reduce leakage risks, HTTPS is generally required.
    • Application scenario: It is usually used on systems that do not require high internal security, such as the router web page management interface
    • Question:
      1. Requests carry authentication information and are easily sniffed
      2. Can’t cancel
  • Cookie + Session:
    • Summary:
      • The server stores the session, and the client stores the cookie, which stores the sessionID
      • Revoke permissions flexibly and synchronize session contents conveniently after updating information
      • Distributed sessions typically use Redis (or other KV) storage
    • Application scenario: Suitable for independent authentication in traditional systems
  • JWT:
    • Summary:
      • Servers do not need to store sessions, so server authentication and authentication services can be easily expanded
      • JWT does not rely on cookies and can also be passed using headers
      • To reduce theft, use HTTPS protocol for transmission
    • Applicable scenarios:
      • Suitable for simple RESTful API authentication
      • Suitable for one-time validation, such as registration activation links
    • Question:
      1. A token cannot be discarded during use. The token is valid all the time
      2. The delivered token cannot be synchronized when the payload information is updated
  • Request:
    • Summary:
      • OAuth is an open standard that allows users to authorize third-party applications to access their information stored on another service provider without having to provide user names and passwords to third-party mobile applications or share all the content of their data.
      • GitHub OAuth document identifies and authorizes users for GitHub Apps
    • Applicable scenarios:

      OAuth is divided into the following four modes
      1. Simplified mode, insecure, suitable for purely static page applications
      2. The authorization code mode is the authorization mode with the most complete functions and rigorous procedures. It is usually used on open platforms of the public network
      3. Password mode, commonly used in internal systems, where the caller is a user.
      4. Client mode, generally API calls between internal systems. Call between two platforms, on a platform basis.