头图

Java interview points to the north! Summary of 13 common interview questions/knowledge points for authentication and authorization! | JavaGuide

JavaGuide
中文

Hello everyone, I'm Guide brother! The Dragon Boat Festival is over, and it's time to start work and study again!

I found that there are many small partners who are not particularly familiar with the knowledge of authentication and authorization, and they are confused about the concepts of Session authentication, JWT and Cookie.

Therefore, based on my daily practical application of this part of learning in the project, I have summarized these 13 related questions and attached detailed answers. Hope it can be helpful to everyone!

What is the difference between authentication and authorization?

This is a question that most people will confuse. First, let’s get to know these two nouns from their pronunciation. Many people confuse their pronunciation. So I suggest you first check how these two words should be pronounced and what their specific meanings are.

To put it simply:

  • Authentication: Who are you.
  • Authorization: What do you have permission to do.

A slightly more formal (long-winded) statement is:

  • Authentication is the credential to verify your identity (such as username/user ID and password). Through this credential, the system can know that you are you, which means that the system exists as a user. Therefore, Authentication is called identity/user authentication.
  • Authorization occurs after Authentication . Authorization, everyone should understand just by looking at the meaning, it mainly controls our access to the system. For example, some specific resources can only be accessed by people with specific permissions, such as admin, and some operations on system resources, such as delete, add, and update, can only be accessed by specific people.

Certification:

Authorization:

These two are generally used in combination in our system to protect the security of our system.

Do you understand the RBAC model?

The most commonly used access control model for system access control is RBAC model .

What is RBAC?

RBAC stands for Role-Based Access Control. This is a way of associating permissions through roles, and the roles are also associated with user authorization.

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

RBAC

In RBAC, permissions are associated with roles, and users get the permissions of these roles by becoming members of appropriate roles. This greatly simplifies the management of permissions.

Usually there are 5 tables related to permission design under RBAC, 2 of which are used to establish the relationship between the tables:

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

Generally speaking, if the system has strict requirements for access control, it will generally choose to use the RBAC model for access control.

I have sorted out the electronic version of books related to computer basics, and those who need it are picked up

What is a cookie? What does a cookie do?

Cookie and Session are both conversational methods used to track the identity of the browser user, but the application scenarios of the two are different.

Wikipedia defines Cookie as follows:

Cookies is the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user.

To put it simply: Cookie stored on the client, generally used to store user information .

Here are some application cases Cookie

  1. We Cookie , and the page can automatically fill in some basic information for you to log in when you visit the website next time. In addition, Cookie can save user preferences, themes and other setting information.
  2. Use Cookie save Session or Token Cookie when sending the request to the backend, so that the backend can get Session or Token . In this way, the current status of the user can be recorded, because the HTTP protocol is stateless.
  3. Cookie can also be used to record and analyze user behavior. For a simple example, when you are shopping online, because the HTTP protocol is stateless, if the server wants to obtain the status of your stay on a certain page or which products you have viewed, a common way to achieve this is to store this information At Cookie
  4. ......

How to use cookies in the project?

Here I take the Spring Boot project as an example.

1) Set Cookie back to the client

@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
    // 创建一个 cookie
    Cookie cookie = new Cookie("username", "Jovan");
    //设置 cookie过期时间
    cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
    //添加到 response 中
    response.addCookie(cookie);

    return "Username is changed!";
}

@CookieValue annotation provided by the Spring framework to get the value of a specific cookie

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

3) Read all Cookie values

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

For more information on how to use Cookie in Spring Boot, please check this article: How to use cookies in Spring Boot .

What is the difference between Cookie and Session?

Session is to record the user's status through the server. typical scenario is a shopping cart. When you want to add an item to the shopping cart, the system does not know which user is operating it, because the HTTP protocol is stateless. Session for a specific user, the user can be identified and tracked.

Cookie data is stored on the client side (browser side), and Session data is stored on the server side. Relatively speaking, Session is more secure. In order to ensure the security of the information in Cookie Cookie information and then go to the server to decrypt it when it is used.

So, how to use Session for authentication?

How to use Session-Cookie scheme for authentication?

Many times we use SessionID to achieve specific users. SessionID generally chooses to store in Redis. for example:

  1. The user successfully logs in to the system, and then returns to the client SessionID with Cookie
  2. When the user initiates a request to the backend, it will bring SessionID , so that the backend knows your identity status.

The more detailed process of this authentication method is as follows:

  1. The user sends the user name, password, and verification code to the server to log in to the system.
  2. After the server is authenticated, the server creates a Session for the user, and stores the Session information.
  3. The server returns a SessionID to the user, and writes the user's Cookie .
  4. When the user remains logged in, Cookie will be sent out with each subsequent request.
  5. The server can be stored in Cookie on SessionID stored in memory in a database or Session when comparing information to verify the user's identity, the client returned to the user response information will be included with the current state of the user.

When using Session , you need to pay attention to the following points:

  1. The key business that relies on Session must ensure that the client has enabled Cookie .
  2. Note the expiration time of Session

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

How to do the Session-Cookie scheme under multiple server nodes?

The Session-Cookie scheme is a very good identity authentication scheme in a single environment. However, when the server level expands to multiple nodes, the Session-Cookie solution will face challenges.

For example: if we deploy two identical services A and B, when the user logs in for the first time, Nginx forwards the user request to the A server through the load balancing mechanism. At this time, the user's session information is stored in the A server. As a result, when the user visits for the second time, Nginx routes the request to server B. Since server B does not save the user's session information, the user needs to log in again.

How should we avoid the above situation?

There are several options for your reference:

  1. All requests of a certain user are assigned to the same server for processing through the characteristic hash strategy. In this case, each server saves part of the user's session information. When the server is down, all the session information saved in it is completely lost.
  2. The Session information saved by each server is synchronized with each other, which means that each server saves the full amount of Session information. Whenever the Session information of a server changes, we will synchronize it to other servers. This solution is too costly, and the more nodes, the higher the synchronization cost.
  3. Separately use a data node (such as a cache) that all servers can access to store Session information. In order to ensure high availability, data nodes should be avoided as much as possible to be single points.

Can Session still be used without cookies?

This is a classic interview question!

Usually through Cookie to save SessionID , if you use Cookie save SessionID program, and if the client is disabled Cookie , then Session will not work.

However, it is not that Cookie cannot be used Session . For example, you can put SessionID in the requested url https://javaguide.cn/?Session_id=xxx . This solution is feasible, but the security and user experience are reduced. Of course, for you, you can also SessionID once and then pass it to the backend.

Why can cookies not prevent CSRF attacks, but tokens?

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

Xiao Zhuang logged in to an online bank. He came to the post area of the online bank. He saw a link below a post that said "Scientific financial management, annual profit rate exceeded 10,000". Xiao Zhuang curiously clicked on this link and found that My account is 10,000 yuan less. Is this the case? It turns out that the hacker hid a request in the link. This request directly used Xiaozhuang's identity to send a transfer request to the bank, that is, send a request to the bank through your Cookie.

<a src=http://www.mybank.com/Transfer?bankId=11&money=10000>科学理财,年盈利率过万</>

As mentioned above, when performing Session authentication, we generally use Cookie to store SessionId . When we log in, the backend generates a SessionId and returns it to the client in a cookie. The server records this through Redis or other storage tools. SessionId , after the client logs in, every request will bring this SessionId , and the server uses this SessionId to mark you as a person. If someone else by Cookie got SessionId after you can substitute your identity to access the system.

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

However, if we use Token , this problem will not exist. After we successfully log in to obtain Token , we generally choose to store it in localStorage (local browser storage). Token to each request sent to the back-end in some way on the front-end, so that there will be no CSRF vulnerabilities. Because even if you click on an illegal link and send a request to the server, the illegal request will not carry Token , so this request will be illegal.

It should be noted that neither Cookie nor Token can avoid the cross-site scripting attack (Cross Site Scripting) XSS .

Cross Site Scripting (Cross Site Scripting) is abbreviated as CSS, but this will be confused with the abbreviation of Cascading Style Sheets (CSS). Therefore, some people abbreviated cross-site scripting attacks as XSS.

In XSS, attackers use various methods to inject malicious code into other users' pages. You can steal information such as Cookie through scripts.

Recommended reading: prevent CSRF attacks? Technical Team 160cb2b4290f5b

What is Token? What is JWT?

In the previous question, we discussed the use of Session to authenticate users, and gave several Spring Session case sharing. We know that Session information needs to be saved on the server side. This method will bring some troubles, for example, we need to ensure Session information server, not suitable for mobile terminals (depending on Cookie ) and so on.

Is there a way to achieve identity verification Session Token use 060cb2b4290fac! the JWT is (JSON Web Token) achieved in this way, this way the server does not need to save Session data, and only in saving the client returned from the server to the client Token on it, would be enhanced scalability .

JWT is essentially a piece of signed JSON format data. Since it is signed, the receiver can verify its authenticity.

The following is a more formal definition of JWT 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 3 parts:

  1. Header : Describe the JWT metadata, define the algorithm for generating the signature and the type of Token
  2. Payload : used to store the actual data that needs to be transferred
  3. Signature : The server uses Payload , Header and a key ( secret ) to use Header (the default is HMAC SHA256) to generate.

How to authenticate based on Token?

In applications based on the Token authenticate the server by Payload , Header and a key ( secret ) creates a token ( Token ) and Token sent to the client, the client Token saved in Cookie localStorage or inside, after All requests from the client will carry this token. You can put it in the Cookie and send it automatically, but this cannot be cross-domain, so it is better to put it in the Authorization field of the HTTP Header: Authorization: Bearer Token .

jwt

  1. The user sends the user name and password to the server to log in to the system.
  2. The authentication service responded and returned a signed JWT containing the content of who the user was.
  3. The user will bring JWT Header every time he sends a request to the backend.
  4. The server checks the JWT and obtains user-related information from it.

What is SSO?

SSO (Single Sign On) means that when a user logs in to one of multiple subsystems, he has the right to access other systems related to it. For example, after we landed on JD Finance, we also successfully landed on JD’s JD Supermarket, JD International, JD Fresh and other subsystems.

sso

What is OAuth 2.0?

OAuth is an industry standard authorization protocol, mainly used to authorize third-party applications to obtain limited permissions. 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 abandoned. For details, please see: rfc6749 .

In fact, it is an authorization mechanism, and its ultimate purpose is to issue a time-sensitive token Token for third-party applications so that third-party applications can obtain related resources through the token.

The most common scenario for OAuth 2.0 is third-party login. When your website is connected to a third-party login, the OAuth 2.0 protocol is generally used.

In addition, now OAuth 2.0 is also commonly used in payment scenarios (WeChat Pay, Alipay Payment) and development platforms (WeChat Open Platform, Ali Open Platform, etc.).

Relevant parameters of WeChat payment account:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-yqIC91bs-1623925796543)(./images/basis-of-authority-certification/WeChat payment-fnglfdlgdfj.png) ]

The following figure is a schematic diagram Slack OAuth 2.0 third-party login

Recommended reading:

The latest version of Java learning route written in half a month has been updated! It may be the most careful and comprehensive Java back-end learning route you have ever seen.

most suitable Java system learning route for novices!

I am Guide brother, embrace open source and like cooking. Open source project JavaGuide author, Github: Snailclimb-Overview . In the next few years, I hope to continue to improve JavaGuide, and strive to help more friends who learn Java! mutual encouragement! Hoo! Click to view my 2020 work report!

Originality is not easy, welcome to like and share, welcome to follow @JavaGuide , I will continue to share original dry goods~

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

阅读 2.1k

JavaGuide
主Java,平时也会发一些新技术比如Python的奇能技巧,机器学习,大数据,区块链等等。 在这里会定期更新...

欢迎关注 Guide哥在segmentfault的账号!本人是 JavaGuide(81k+ Star)的作者,该项目多次登上 Java 类...

8.8k 声望
1.8k 粉丝
0 条评论

欢迎关注 Guide哥在segmentfault的账号!本人是 JavaGuide(81k+ Star)的作者,该项目多次登上 Java 类...

8.8k 声望
1.8k 粉丝
文章目录
宣传栏