Hello, I’m Guide! Dragon Boat Festival has passed, and began to work and study!

I find that many friends do not know much about authentication and authorization, and are confused about the concepts of Session authentication, JWT and Cookie.

Therefore, ACCORDING to the daily application of this part of the study in the project, I have summarized the 13 relevant questions and attached detailed answers. Hope to be helpful to everyone!

What is the difference between Authentication and Authorization?

This is a question that most people are confused about. First of all, from the pronunciation of these two nouns, a lot of people will be confused with their pronunciation, so I suggest you first go to look up these two words exactly how to pronounce, their specific meaning is what.

To put it simply:

  • Authentication: Who you are.
  • Authorization: What do you have the authority to do?

To be a little more formal (or wordy) :

  • Authentication is a credential that authenticates your identity (e.g. username/user ID and password). Through this credential, the system knows that you are you. So Authentication is called identity/user Authentication.
  • Authorization occurs after Authentication. Licensing, as you can see from the meaning, is basically how much access we have to the system. For example, some specific resources can only be accessed by people with specific permissions, such as admin. Some operations on system resources, such as deleting, adding and updating, can only be accessed by specific people.

Certification:

Authorization:

These two are usually used together in our system to protect the security of our system.

Do you understand the RBAC model?

RBAC is the most commonly used access control model for system permission control.

What is RBAC?

RBAC is role-based Access Control. This is a way to associate permissions with roles, and roles are also associated with user permissions.

To put it simply: a user can have several roles, and each role can be assigned several permissions. Thus, a “user-role-permission” authorization model is constructed. In this model, a many-to-many relationship is formed between users and roles, and between roles and permissions, as shown in the following figure

In RBAC, permissions are associated with roles, and users gain permissions for those roles by becoming a member of the appropriate roles. This greatly simplifies permission management.

Normally, there are 5 tables related to permission design under RBAC, and 2 of them are used to establish connections between tables:

With this permission model, we can create different roles and assign different permission scopes (menus) to different roles.

Generally speaking, if the system has strict permission control requirements, it will choose to use the RBAC model to do permission control.

I have sorted out the electronic version of computer basic related books

What is a Cookie? What does a Cookie do?

Cookies and sessions are both used to track the identity of a browser user, but they are used in different scenarios.

Wikipedia defines cookies as follows:

Cookies are data stored (usually encrypted) on a user’s local terminal by some web sites to identify the user.

To put it simply: Cookies are stored on the client and are generally used to save user information.

Here are some examples of cookies in use:

  1. We are inCookieSave has logged in the user information, the next time you visit the site page can automatically help you log in some basic information to fill. In addition to that,CookieIt also saves user preferences, themes, and other Settings.
  2. useCookiesaveSessionorToken, when sending requests to the back endCookie, so that the back end can fetchSessionorToken. This keeps track of the user’s current state, since the HTTP protocol is stateless.
  3. CookieIt can also be used to record and analyze user behavior. A simple example is when you’re shopping online. Because HTTP is stateless, if the server wants to know how long you’ve been on a page or what items you’ve looked at, a common way to do that is to store that informationCookie
  4. .

How do you use cookies in your project?

I’ll use the Spring Boot project as an example.

1) setCookieReturn to the client

@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
    // Create a cookie
    Cookie cookie = new Cookie("username"."Jovan");
    // Set the cookie expiration time
    cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
    // Add to response
    response.addCookie(cookie);

    return "Username is changed!";
}
Copy the code

2) Using the Spring framework@CookieValueThe annotation gets the value of a particular cookie

@GetMapping("/")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}
Copy the code

3) Read allCookie

@GetMapping("/all-cookies")
public String readAllCookies(HttpServletRequest request) {

    Cookie[] cookies = request.getCookies();
    if(cookies ! =null) {
        return Arrays.stream(cookies)
                .map(c -> c.getName() + "=" + c.getValue()).collect(Collectors.joining(","));
    }

    return "No cookies";
}
Copy the code

For more information on How to use cookies in Spring Boot, see this article: How to Use Cookies in Spring Boot.

What’s the difference between cookies and sessions?

The main purpose of a Session is to record user status through the server. A typical scenario is a shopping cart. When you add an item to the cart, the system doesn’t know which user is doing it because the HTTP protocol is stateless. After creating a specific Session for a particular user, the server can identify that user and keep track of that user.

Cookie data is stored on the client (browser) and Session data is stored on the server. Session security is relatively higher. In order to ensure the security of the Cookie information, it is best to encrypt the Cookie information and decrypt it on the server when it is used.

So, how do you use itSessionAuthentication?

How do I use the session-cookie scheme for authentication?

Most of the time we implement a specific user with a SessionID, and the SessionID is stored in Redis. Here’s an example:

  1. The user successfully logs in to the system and then returns to the client withSessionIDCookie
  2. When the user makes a request to the back end, it will send theSessionIDSo the back end knows your status.

The more detailed process of this authentication is as follows:

  1. The user sends the user name, password, and verification code to the server for logging in to the system.
  2. After the server is authenticated, the server creates one for the userSessionAnd willSessionInformation is stored.
  3. The server returns one to the userSessionID, written to the userCookie.
  4. While the user remains logged in,CookieWill be sent out with each subsequent request.
  5. The server can store theCookieOn theSessionIDAnd stored in memory or databaseSessionInformation is compared to verify the user’s identity, and the client response is returned to the user with the current status of the user.

Note the following when using sessions:

  1. Rely onSessionMake sure the client is enabled for your critical businessCookie.
  2. Pay attention toSessionThe expiration time of.

In addition, Spring Session provides a mechanism for managing user Session information across multiple applications or instances. If you want to learn more, check out the following excellent articles:

  • Getting Started with Spring Session
  • Guide to Spring Session
  • Sticky Sessions with Spring Session & Redis

How do I implement the session-cookie scheme on multiple server nodes?

Session-cookie scheme is a very good identity authentication scheme in monomer environment. However, when servers scale horizontally to multiple nodes, the session-cookie scheme becomes challenging.

For example, if we deploy two identical services A and B, when users log in for the first time, Nginx forwards user requests to server A through load balancing mechanism, and user Session information is stored in server A. As a result, Nginx routes the request to server B on the user’s second attempt. Since server B does not store the user’s Session information, the user needs to log in again.

How can we avoid the above situation?

There are several options for you to consider:

  1. All requests from a user are assigned to the same server through the feature’s hash policy. In this way, each server keeps a portion of the user’s Session information. When the server goes down, all of its saved Session information is completely lost.
  2. The Session information stored on each server is synchronized with each other, that is, each server stores the full amount of Session information. Whenever the Session information on one server changes, we synchronize it to the other servers. This scheme is too expensive, and the more nodes there are, the higher the synchronization cost is.
  3. Use a single data node (such as a cache) that all servers can access to store Session information. To ensure high availability, data nodes should avoid being single points.

Student: Would sessions work if there were no cookies?

This is a classic interview question!

Session ids are normally stored in cookies. If you use a Cookie to store Session ids, if the client disables cookies, the Session will not work properly.

However, it is not impossible to use a Session without cookies. For example, you can put the SessionID in the requested URL https://javaguide.cn/?Session_id=xxx. This scheme is feasible, but the security and user experience is reduced. Of course, you can encrypt the SessionID once and pass it to the back end.

Why do cookies not protect against CSRF attacks, but tokens do?

Cross Site Request Forgery (CSRF) is generally translated as cross-site Request Forgery. So what is cross-site request forgery? Simply use your identity to send unfriendly requests. Here’s a simple example:

Small strong login to an online bank, he came to the online bank’s post area, see a post below a link written “scientific financial management, annual profit rate of more than 10,000”, small strong curious click on the link, the result found his account less 10,000 yuan. How could this be? It turns out that the hacker hid a request in the link, which directly used Xiao Zhuang’s identity to send a transfer request to the bank, that is, through your Cookie to send a request to the bank.

<a src=http://www.mybank.com/Transfer?bankId=11&money=10000>Scientific financial management, annual profit rate of more than 10,000</>
Copy the code

As mentioned above, during Session authentication, we generally use cookies to store the SessionId. When we log in, the backend generates a SessionId and returns it to the client in the Cookie. The server uses Redis or some other storage tool to record the SessionId. After logging in, the client will carry this SessionId with each request. The server uses this SessionId to identify you. If someone else gets a SessionId through a Cookie, they can access the system on your behalf.

The SessionId in the Cookie of Session authentication is sent to the server by the browser. With this feature, the attacker can make the user click the attack link to achieve the attack effect.

However, this problem does not exist if we use tokens. After logging in and obtaining tokens, we usually choose to store them in localStorage (browser localStorage). We then add this Token to each request sent to the back end in some way on the front end so that CSRF vulnerabilities do not occur. Because, even if one of you clicked the illegal link and sent the request to the server, the illegal request would not carry the Token, so the request would be illegal.

Note that neither cookies nor tokens are immune to Cross Site Scripting XSS.

Cross Site Scripting is abbreviated CSS but this can confuse the abbreviation for Cascading Style Sheets (CSS). For this reason, cross-site scripting attacks have been abbreviated to XSS.

In XSS, attackers can inject malicious code into other users’ pages in various ways. You can use scripts to steal information like cookies.

Recommended Reading: How to Prevent CSRF Attacks? — Meituan technical team

What’s a Token? JWT is what?

We discussed the use of sessions to authenticate users in the previous question and gave several examples of Spring Sessions. We know that Session information needs to be stored on the server. This approach has some complications, such as requiring us to ensure the availability of the server that stores Session information, not suitable for mobile (relying on cookies), etc.

Is there a way to authenticate without having to store Session information yourself? Use Token! JWT (JSON Web Token) is implemented in this way. In this way, the server does not need to save Session data, but only saves the tokens returned by the server to the client, which improves scalability.

JWT is essentially a signed piece of JSON-formatted data. Since it is signed, the recipient can verify its authenticity.

The following is a more formal definition of JWT in RFC 7519.

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or Encrypted. — JSON Web Token (JWT)

JWT consists of three parts:

  1. Header: describes the metadata of the JWT, defines the algorithm for generating signatures andTokenThe type of.
  2. Payload: Stores the data that needs to be transmitted
  3. Signature (= Signature): The server passes.Payload,HeaderAnd a key (secret) to useHeaderThe signature algorithm specified in it (HMAC SHA256 by default) is generated.

How to authenticate based on Token?

In token-based authentication applications, the server creates a Token using Payload, Header, and a secret and sends the Token to the client. The client saves the Token in a Cookie or localStorage. All subsequent requests from the client carry the Token. You can put it in a Cookie and send it automatically, but that’s not cross-domain, so it’s better to put it in the HTTP Header Authorization field: Bearer Token.

  1. A user sends a user name and password to the server to log in to the system.
  2. The authentication service responds and returns the signed JWT, which contains information about who the user is.
  3. Each subsequent request from the user to the backend will be presentHeaderMiddle with JWT.
  4. The server checks the JWT and retrieves user-related information from it.

What is the SSO?

SSO(Single Sign On) means that a user logs in to one of multiple subsystems and has access to other systems related to it. For example, after we landed on JINGdong Finance, we also successfully landed on jingdong supermarket, Jingdong International, Jingdong fresh and other subsystems.

What is OAuth 2.0?

OAuth is an industry standard licensing protocol used to grant limited permissions to third-party applications. OAuth 2.0 is a complete redesign of OAuth 1.0. OAuth 2.0 is faster and easier to implement. OAuth 1.0 has been scrapped. For details, see RFC6749.

In fact, it is a kind of authorization mechanism, and its ultimate purpose is to issue a time-sensitive Token to the third party application, so that the third party application can obtain relevant resources through this Token.

A common scenario of OAuth 2.0 is third-party login. When your website is connected to third-party login, it usually uses the OAuth 2.0 protocol.

In addition, OAuth 2.0 is now common in payment scenarios (wechat Pay, Alipay Pay) and development platforms (wechat Open platform, Ali Open platform, etc.).

Wechat Pay account parameters:

[Img-yQIC91BS-1623925796543] /images/ basis-of-authority-Certification/wechat Payment-fnGLfdLGdf j.png)]

Here is a schematic of Slack OAuth 2.0 third-party login:

Recommended reading:

  • A brief explanation of OAuth 2.0
  • What is OAuth 2.0 protocol
  • OAuth 2.0 in four ways
  • GitHub OAuth third-party login example tutorial

The latest version of Java learning route, which took half a month to write, has been updated! Probably the most thoughtful and comprehensive Java backend learning path you’ve ever seen.

Most suitable for novice Java system learning route!

I’m Guide, embrace open source and love to cook. Author of JavaGuide, Github: Snailclimb-Overview. In the next few years, I hope to continue to improve JavaGuide, and strive to help more people learn Java! ‘! 凎! Click here for my 2020 work Report!

Original is not easy, welcome to like to share, welcome to follow @Javaguide, I will continue to share original dry goods ~

This answer is my own original, if you need to reprint, also please indicate the source ah!