When we log in to a website, we often record the login status or visit the third party website, and do not know how to realize interaction. The following is a detailed analysis of several methods and comparison between them, including Session, Token, JWT and OAuth2. Start by summarizing the main points and introducing the details.

Categorically speaking,

  • Session is an authentication mechanism
  • Token and JWT are authentication and authorization mechanisms
  • OAuth2 is the authorization framework

In terms of application scenarios,

  • Session: your own simple website;
  • Token: Distributed, cross-system, single sign-on, allowing third parties to call API interfaces, user data needs to be shared with third parties, etc., are not suitable for implementation.
  • JWT: Scenarios can be the same as tokens, but the implementation logic for obtaining authentication tokens is different
  • OAuth2: Authorize third-party applications and multi-platform single sign-on

In terms of implementation,

  • Session: Based on cookies and sessionids
  • Token Token: uid (user unique identity) + timestamp (current timestamp) + sign (signature)
  • JWT token: header + payload + sign
  • OAuth2: based on the authorization code, client_id, client_secret, etc

The difference between Session and Cookie

  • Security: The Session is more secure than the Cookie. The Session is stored on the server and the Cookie is stored on the client.

  • The value types are different: Cookies only support string data. If you want to set other types of data, you need to convert them into strings. Session can store any data type.

  • Different validity periods: Cookies can be set to hold for a long time. For example, the default login function that we often use, the Session usually expires for a short time, and the client shuts down (by default) or the Session times out will be invalid.

  • Different storage sizes: The data stored by a single Cookie cannot exceed 4K, and the data stored by a Session is much higher than that stored by cookies. However, if there are too many visits, too many server resources will be occupied.

Token and Session

Session information

The Session Information window displays all users currently logged in to Access Manager and the session time of each user. The fields displayed include:

The user ID. The user ID of the current login user is displayed.

Remaining time. Displays the time (in minutes) left for the session before reauthentication is required.

Maximum session time. Displays the maximum amount of time, in minutes, that a user can log in before the session expires and must be reauthenticated to regain access.

Free time. Displays how long the user is idle, in minutes.

Maximum idle time. Displays the maximum amount of time, in minutes, that a user can be idle before reauthentication is required.

Time limits are defined by the administrator in Session Management Services.

Enter a string in the User ID field, and then click Filter to display a specific user session or a specific part of the user session. Wildcard characters are allowed.

You can also view detailed information about the login, such as the source IP address, login time, and logout time.

Token token consists of:

  • Uid: indicates the unique user identity
  • Timestamp: indicates the current timestamp
  • Sign: indicates the signature string to prevent the third party from forging data. The signature key is stored on the server side and cannot be known by other people
  • Additional parameters.

The difference between Token and Session

  • Token is generated by identity information and signature, and is transmitted to the client as a whole. A sessionId is a random number generated by the server after the client logs in.
  • Client: Token and sessionId can be stored in Cookie and LocalStorage.
  • Server: For tokens, the private key is the signature stored in the database, but does not store some of the session information; The sessionId and the client information represented by the sessionId are stored in memory or database (usually in memory database).
  • Token isThe response body is returned to the client, stored in cookies, localstorage, etc.It is not carried by default when requested again, can carry tokens in request header Authorization;The sessionId is set by the server in the cookie, and the client carries it with it by default on every request.
  • Session is a mechanism for recording the Session status between the server and the client. The server is stateful and can record Session information. Tokens are tokens, resource credentials needed to access resource interfaces (apis). Token makes the server stateless and does not store session information.
  • Session and Token are not contradictory,Token as authentication is more secure than SessionBecause each request is signed and protects against listening and replay attacks, sessions must rely on the link layer for communication security. If you need to implement stateful sessions, you can still add sessions to store some state on the server side.
  • Tokens are tokens that represent permission to perform certain operations, if OAuth tokens or similar mechanisms that provide authentication and authorization,Authentication is for the user, authorization is for the App,itsThe goal is to give an App the right to access a user's information. Token is unique. It cannot be transferred to other apps or to other users.Session provides only a simple authentication, that is, as long as the SessionID is present, the User is considered to have full rights. (So in a nutshell:If your user data may need to be shared with a third party, or allow third parties to call apis, use tokens. If it's always just your own website, your own App, what does it matter).

Think back to the data link layer? Because why does a session guarantee security at the link layer?

Why do most people choose tokens instead of sessions?

  • The client browser only needs to store its own Session ID, while the server needs to store all users’ Session information, which is expensive for the server and does not take advantage of the server’s extensions.

  • In addition, the sessionId is stored in the client, so it is easy to initiate malicious requests, which is not secure. Of course, the token signature cannot be stolen, so it is not safe to set the expiration time too long.

  • Cookie/Session on a single server, single domain is relatively simple, otherwise, you need to consider how to save or synchronize the client session to multiple servers. Also consider whether this information will be lost in memory in the event of an outage. Token Because the server does not store user identities, this problem does not exist and is more conducive to distributed deployment

conclusion

  • Cookie: saved in the browser, size limit, stateless; There are no special restrictions on cookies, which the client carries with it by default on every request.

  • Session: stored in the server. The server has resource overhead, distributed, cross-system, single sign-on (SSO), allows third parties to call API interfaces, and user data needs to be shared with third parties.

  • Token: Clients can store tokens anywhere, without limit and stateless, which facilitates distributed deployment.

  • Sessionids are a bridge between cookies and sessions

  • If it’s your own simple site, use sessions. If the system has multiple simultaneous login users and multiple cluster servers, and sso requirements are required, the token is preferred.

JWT

What is the JWT

  • The JSON Web Token (JWT for short) isCurrently the most popular cross-domain authentication solution.
  • JWT is an open jSON-based standard (RFC 7519) implemented for passing declarations between network application environments. JWT declarations are typically used to pass authenticated user identity information between the identity provider and the service provider to facilitate resource retrieval from the resource server. For example, for user login.
  • JWT can be signed using either the HMAC algorithm or RSA’s public/private key. These messages are trusted because of digital signatures.

WT (Web Token)

The WT contains three parts: Header Header, Payload Payload, and Signature Signature. Three parts are used to generate the token. Number to do the partition.

  1. Header The Header contains two parts: Type: indicates the token type. In this case, the JWT type is used. Alg: indicates the Hash algorithm used, for example, HMAC SHA256 or RSA.

    {” ALG “: “HS256”, “TYP “: “JWT”} this will be base64Url encoded into the first part

  2. The second part of the Payload token is the Payload information. It contains a Claim(a description of an entity, usually a User information, and other metadata).

  • Reserved Claims: This is a set of predefined Claims that are not required. It is an easy to use and operational set of Claims. The value can be iss(Issuer), EXP (expiration time), Sub (subject), and AUD (audience).
  • Plubic Claims;
  • {“sub”: “1234567890”, “name”: “John Doe”, “admin”: true} Also Base64Url encoded to form the second part
  1. Signature Encrypts the encoded header, payload, and secret using the algorithm specified in the header. For example, HMAC SHA256 algorithm is used, and the general process is similar to: HMACSHA256(base64UrlEncode(header) + “.” + base64UrlEncode(Payload), secret) This signature field is used to identify the sender of a JWT message and ensure that the message has not been modified.

JWT certification process

  • After a user enters the user name and password to log in, the server returns a JWT to the client after successful authentication
  • The client saves the token locally (usually using localstorage, but can also use cookies)
  • When a user wishes to access a protected route or resource, the JWT is added using a Bearer mode in the Authorization field of the request header, which looks like this

Authorization: Bearer

Difference between Token and JWT

The same:

  • Both are authentication and authorization mechanisms (or tokens). Clients can access protected resources on the server only after the authentication succeeds
  • Can record user information
  • Both are stateless authentication mechanisms on the server because the user’s state is no longer stored in server memory

The difference between:

  1. The token algorithm is different

Tokens include: uid (unique user identification) + timestamp (current timestamp) + sign (signature)

WT contains: header + payload + sign

  1. Storage location on the client

In general, JWT does not use cookies and is placed in request header Authorization, while tokens are stored in cookies.

Since JWT does not use cookies, you can use any domain name to provide your API services without worrying about cross-domain resource sharing (CORS).

  1. Whether to query the database
  • Token: When the server authenticates the Token sent by the client,You also need to query the database for user information and verify that the Token is valid.
  • JWT:The Token and Payload are encrypted and stored on the client, the server only needs to use key decryption for verification (verification is also implemented by JWT itself).No queries or reduced queries to the database are requiredBecause JWT contains both user information and encrypted data.

JWT does not need to query the database. JWT does not need to query the database. JWT directly uses the secret key to verify the server.

OAuth

In OAuth2.0 “O” is short for Open, meaning “Open”. OAuth is an open network standard about authorization, which is widely used all over the world. In one sentence, OAuth2.0 is an authorization protocol.

OAuth allows users to grant third-party applications access to their data stored on other services without requiring them to provide a username and password.

Eg: Applications developed in Flying Book are login free in flying Book

In summary: OAuth2.0 is a licensing protocol that ensures that third party applications can only further access authorizer data after obtaining authorization.

The third-party application first applies for an authorization code, then uses the authorization code to obtain a token, and finally uses the token to obtain resources. The authorization code mode is the most complete authorization mode with the most rigorous process. It is characterized by interaction with the authentication server of the service provider through the backend server of the client.

The log-in free for flying books is also OAuth2.0 logic

function getCode() {
    let code = getUrlParam("code");
    console.log("code:", code);
    if (code) {
      getUseInfo(code);
    } else {
      window.location.href =
        "https://open.work.sany.com.cn/open-apis/authen/v1/user_auth_page?app_id=cli_a0b221d078389076&redirect_uri=http%3A%2F%2F 222.240.242.218%3 a8888%2 fdevice % 2 f"; }}Copy the code

Authorization code time is very short, fly book only set up 1 minute, before getting 2 minutes.

Once we get the authorization code, our server will go to the authentication server and request the data.

https://server.example.com/oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&cod e=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URLCopy the code

Request parameters:

  • Client_id: indicates the ID of a client registered with the service provider.
  • Client_secret: specifies the secret key of the authorization server, registered with the service provider by third-party applications.
  • grant_type: value isAUTHORIZATION_CODE, indicates that the authorization mode is an authorization code.
  • Code: indicates the authorization code obtained in the previous step.
  • Redirect_uri: The redirect_URI parameter is the callback url after the token is issued and must be the same as the value in step A.

Note: The client_id parameter and the client_secret parameter are used to allow B to confirm A’s identity.

The company can use OAuth on so many platforms that only one user can log in and no other application can log in.

Authorization mode of OAuth2.0

  • Authorization Code
  • Simplified patterns (Implicit)
  • Password mode (Resource owner Password Credentials)
  • Client credentials

Specific implementation logic reference: www.jianshu.com/p/a0905113b…

Difference between JWT and OAuth2

  1. The function attributes are different
  • JWT is an authentication protocol that verifies user access to resources
  • OAuth2 is an authorization framework that provides a detailed authorization mechanism (guidance) for granting third-party applications access to specific resources.
  1. Application scenarios are different
  • JWT is used when the front and back end are separated and the background API needs to be protected simply
  • OAuth2 is used when logging in with a third-party account (such as logging in to an app using Weibo, QQ or Github).

OAuth2 is a relatively complex protocol with four authorization modes. The Access Code mode can be implemented using JWT to generate code or not, and there is no necessary connection between them. OAuth2 has client and scope concepts, JWT does not.

In many cases, the JSON Web Token is used as an authentication mechanism when discussing the implementation of OAuth2.

The end of the I

When we log in to a website, we often record the login status or visit the third party website, and do not know how to achieve interaction. The above specific analysis of several methods and comparison between them, including Session, Token, JWT and OAuth2.

Categorically speaking,

  • Session is an authentication mechanism
  • Token and JWT are authentication and authorization mechanisms
  • OAuth2 is the authorization framework

In terms of application scenarios,

  • Session: your own simple website;
  • Token: Distributed, cross-system, single sign-on, allowing third parties to call API interfaces, user data needs to be shared with third parties, etc., are not suitable for implementation.
  • JWT: Scenarios can be the same as tokens, but the implementation logic for obtaining authentication tokens is different
  • OAuth2: Authorize third-party applications and multi-platform single sign-on

In terms of implementation,

  • Session: Based on cookies and sessionids
  • Token Token: uid (user unique identity) + timestamp (current timestamp) + sign (signature)
  • JWT token: header + payload + sign
  • OAuth2: based on the authorization code, client_id, client_secret, etc

Note:

  • Cookie is not one of the identity authentication methods. Both session and token can be authenticated based on cookie.

  • Authentication is for the user, authorization is for the App or website.

www.jianshu.com/p/f31ef35eb…