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

Time:2021-7-28

Hello, I’m brother! The Dragon Boat Festival is over, and I have to start working and studying again!

I found that many small partners don’t know much about authentication and authorization, and can’t understand the concepts of session authentication, JWT and cookie.

Therefore, according to my daily application of this part of learning in the project, I summarized these 13 relevant questions and attached detailed answers. Hope to be helpful to you!

What is the difference between authentication and authorization?

This is a problem that most people will confuse. First of all, recognize these two nouns from their pronunciation. Many people will confuse their pronunciation, so I suggest you first check how to pronounce these two words and what their specific meaning is.

To put it simply:

  • Authentication:who are you.
  • Authorization:What do you have authority to do.

A little more formal (wordy) is:

  • AuthenticationIt is the credential to verify your identity (such as user name / user ID and password). Through this credential, the system can know that you are you, that is, you exist in the system. Therefore, authentication is called authentication / user authentication.
  • Authorizationhappen toAuthenticationAfter that. Authorization, just look at the meaning, you should understand that it is mainly in charge of our access 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 delete, add and update, can only be accessed by specific talents.

authentication:

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

to grant authorization:

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

These two are generally used together 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 permission control isRBAC model

What is RBAC?

RBAC is role-based access control. This is a way to associate permissions through roles, and roles are associated with user authorization at the same time.

Simply put, a user can have several roles, and each role can be assigned several permissions. In this way, an authorization model of “user role permission” is constructed. In this model, many to many relationships are formed between users and roles, roles and permissions, as shown in the following figure

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

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

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

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

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

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

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

I have sorted out the electronic version of books related to computer foundation. I need my little partner to take it by myself
Java interview points north! Summary of 13 common interview questions / knowledge points for certification and authorization| JavaGuide

What is a cookie? What is the role of cookies?

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

CookieandSessionBoth are session methods used to track the identity of browser users, but their application scenarios are different.

Wikipedia is defined like thisCookieOf:

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

In short:CookieIt is stored in the client and is generally used to save user information

Here isCookieSome application cases:

  1. We areCookieSave the logged in user information in. The next time you visit the website, the page can automatically fill in some basic information for you to log in. besides,CookieIt can also save user preferences, themes and other setting information.
  2. useCookiepreservationSessionperhapsTokenWhen the request is sent back and upCookie, so that the back end can getSessionperhapsTokenYes. In this way, the current state of the user can be recorded, because the HTTP protocol is stateless.
  3. CookieIt can also be used to record and analyze user behavior. For example, when you shop online, because the HTTP protocol is stateless, if the server wants to get your stay status on a page or what products you see, a common implementation method is to store this information in theCookie
  4. ……

How do I use cookies in my project?

Let me take the spring boot project as an example.

1) SetCookieReturn to client

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

    return "Username is changed!";
}

2) Using the spring framework@CookieValueAnnotation gets 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 allCookievalue

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

More about how to use in spring bootCookieYou can view this article:How to use cookies in Spring Boot

What is the difference between a cookie and a session?

SessionThe main function of is to record the user’s status through the server.A typical scenario is a shopping cart. When you want to add goods to the shopping cart, the system does not know which user operates, because the HTTP protocol is stateless. The server creates a specific for a specific userSessionThen you can identify the user and track the user.

CookieThe data is saved in the client (browser),SessionThe data is saved on the server side. relatively speakingSessionHigher security. To ensureCookieFor the security of information in, it is best toCookieThe information is encrypted and then decrypted on the server when it is used.

So, how to useSessionAuthenticate?

How to use session cookie scheme for authentication?

Many times we passSessionIDTo implement specific users,SessionIDIt is usually stored in redis. for instance:

  1. The user successfully logs in to the system, and then returns to the client withSessionIDYesCookie
  2. When the user makes a request to the back end, theSessionIDTake it with you so that the back end will know your identity status.

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

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

  1. The user sends the user name, password and authentication code to the server to log in to the system.
  2. After the server passes the authentication, the server creates one for the userSession, andSessionStore information.
  3. The server returns a message to the userSessionID, write user’sCookie
  4. When the user remains logged in,CookieWill be sent with each subsequent request.
  5. The server can storeCookieUpperSessionIDAnd stored in memory or databaseSessionInformation is compared to verify the user’s identity. When the client response information is returned to the user, the current state of the user will be attached.

useSessionYou should pay attention to the following points:

  1. rely onSessionMake sure that the client is turned onCookie
  2. be carefulSessionThe expiration time of the.

In addition, spring session provides a mechanism to manage user session information across multiple applications or instances. If you want to learn more, you can check the following good articles:

What is the session cookie scheme for multi server nodes?

Session cookie scheme is a very good authentication scheme in single environment. However, when the server level is expanded to multi nodes, the session cookie scheme 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 server a through the load balancing mechanism. At this time, the user’s session information is saved in server a. As a result, when the user accesses the second time, nginx routes the request to the B server. Because the B server does not save the user’s session information, the user needs to log in again.

How can we avoid the above situation?

There are several schemes for your reference:

  1. All requests of a user are allocated to the same server for processing through the hash policy of the feature. In this way, each server saves a part of the user’s session information. When the server goes down, all session information saved by it is completely lost.
  2. The session information saved by each server is synchronized with each other, that is, each server saves the full amount of session information. Whenever the session information of one server changes, we synchronize it to other servers. This scheme costs too much, and the more nodes, the higher the synchronization cost.
  3. Use a single data node (such as cache) that can be accessed by all servers to store session information. In order to ensure high availability, data nodes should try to avoid single points.

Can session work without cookies?

This is a classic interview question!

Usually throughCookieTo saveSessionID, if you useCookiepreservationSessionIDIf the client is disabledCookie, thenSessionIt won’t work properly.

However, it is not withoutCookieYou can’t use it laterSessionFor example, you canSessionIDPut in the requestedurlinsidehttps://javaguide.cn/?Session_id=xxx。 This scheme is feasible, but the security and user experience are reduced. Of course, you can do it for youSessionIDEncryption is performed once and then passed to the back end.

Why cookies can’t prevent CSRF attacks, but tokens can?

CSRF(cross site request forge) is generally translated asCross-site request forgery 。 So what isCross-site request forgery And? Simply use your identity to send some unfriendly requests to you. Take a simple example:

Xiaozhuang logged in to an online bank. He came to the post area of online bank and saw a link under a post that said “scientific financial management, annual profit rate of more than 10000”. Xiaozhuang curiously opened this link and found that his account was 10000 yuan less. Is that what happened? Originally, the hacker hid a request in the link. This request directly sent a transfer request to the bank using Xiaozhuang’s identity, that is, send a request to the bank through your cookie.

<a src= http://www.mybank.com/Transfer?bankId=11&money=10000 >Scientific financial management with annual profit rate of over 10000 < / >

As mentioned above, theSessionWe usually use it for certificationCookieTo storeSessionId, when we log in, the backend generates aSessionIdPut it in the cookie and return it to the client. The server records and saves this information through redis or other storage toolsSessionId, the client will bring this with each request after logging inSessionId, the server passes thisSessionIdTo mark you. If someone else passesCookieGot itSessionIdThen you can access the system instead of your identity.

SessionUnder certificationCookieMediumSessionIdIt is sent to the server by the browser. With this feature, the attacker can achieve the attack effect by allowing the user to delay the attack link.

However, we useTokenIf we log in successfully, we won’t have this problemTokenAfter that, it is generally stored inlocalStorage(browser local storage). Then we add this to each request sent to the back end in some ways on the front endTokenIn this way, CSRF vulnerabilities will not occur. Because even if you click an illegal link and send a request to the server, the illegal request will not be carriedTokenYes, so this request will be illegal.

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

It should be noted that whetherCookiestillTokenCan’t be avoidedCross site scripting XSS

Cross site scripting is abbreviated as CSS, but it will be confused with the abbreviation of cascading style sheets (CSS). Therefore, someone abbreviated cross site scripting attack as XSS.

In XSS, attackers can inject malicious code into other users’ pages in various ways. You can steal information through scripts, such asCookie

Recommended reading:How to prevent CSRF attacks? – Meituan technical team

What is a token? What is JWT?

We discussed the use of in the previous questionSessionTo identify the user’s identity, and gives several spring session cases to share. We knowSessionA copy of the information needs to be saved on the server side. This method will bring some troubles, for example, we need to ensure preservationSessionAvailability of information server, unsuitable for mobile terminal (dependent)Cookie)Wait.

Is there one that doesn’t need to be stored by yourselfSessionHow can information be authenticated? useTokenJust!JWT(JSON web token) is the implementation of this method. In this way, the server does not need to saveSessionThe data is saved only on the client and returned to the client by the serverTokenIt’s OK, and the scalability is improved.

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

Here isRFC 7519A more formal definition of JWT.

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. HeaderDescribes the metadata of JWT and defines the algorithm for generating signaturesTokenType of.
  2. Payload: used to store the actual data to be transferred
  3. Signature: via serverPayloadHeaderAnd a key(secret)UseHeaderThe signature algorithm specified therein (HMAC sha256 by default) is generated.

How to authenticate based on token?

In the application of token based authentication, the server passesPayloadHeaderAnd a key(secret)Create token(Token)And willTokenSend to the client, the client willTokenIt is stored in a cookie or localstorage. In the future, all requests sent by the client will carry this token. You can send it automatically in the cookie, but it can’t cross domains, so it’s better to put it in the authorization field of HTTP header:Authorization: Bearer Token

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

  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 that contains who the user is.
  3. Every time the user sends a request to the back end in the futureHeaderBring JWT in.
  4. The server checks JWT and obtains user related information from it.

What is SSO?

SSO (single sign on) means that a user who logs in to one of multiple subsystems has the right to access other systems related to it. For example, after landing Jingdong finance, we also successfully landed Jingdong supermarket, Jingdong international, Jingdong fresh food and other subsystems.

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

What is OAuth 2.0?

OAuth is an industry standard authorization protocol, which is 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, see:rfc6749

In fact, it is an authorization mechanism. Its ultimate purpose is to issue an timeliness token for the third-party application, so that the third-party application can obtain relevant resources through the token.

A common scenario in OAuth 2.0 is the third-party login. When your website accesses the third-party login, the OAuth 2.0 protocol is generally used.

In addition, OAuth 2 is also commonly seen in payment scenarios (WeChat payment, Alipay payment) and development platform (WeChat open platform, Ali open platform, etc.).

Relevant parameters of wechat payment account:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yqc91bs-1623925796543) (. / images / basis of authority certification / wechat payment – fnglfdlgdfj. PNG)]

The following figure isSlack OAuth 2.0 third party loginSchematic diagram of:

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

Recommended reading:

It took half a month to write the latest version of java learning route, which is nearly updated! It may be the most attentive and comprehensive Java back-end learning route you have ever seen.

The most suitable learning route for novice java system!

I’m brother guide. I embrace open source and like cooking. Open source projectJavaGuideAuthor, GitHub:Snailclimb – Overview。 In the next few years, I hope to continue to improve the javaguide and strive to help more small partners learning java! Encourage each other! 凎!Click to view my 2020 work report!

It’s not easy to be original. You’re welcome to like and share. You’re welcome to pay attention@JavaGuide, I will continue to share the original dry goods~

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

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]