Last week I wrote a Demo for beginners to get started With Spring Security With JWT. Demo address: github.com/Snailclimb/… . Many of you may not be familiar with some of the most common concepts in the authentication world, so I wrote an article to introduce them. There may be recommended articles for each part of the knowledge, read the original text to see the link to the article.

1. 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.

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

2. What is Cookie? What does a Cookie do? How do I use cookies on the server side?

2.1 What is 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 “data stored (usually encrypted) on a user’s local terminal by some web site 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 save the user information that has logged in in the Cookie, and the page will automatically fill in some basic information for you when you visit the website next time. In addition, cookies can store user preferences, themes, and other Settings.
  2. A Cookie is used to save the session or token. The Cookie is carried when the request is sent to the backend, so that the backend can obtain the session or token. This keeps track of the user’s current state, since the HTTP protocol is stateless.
  3. Cookies can also be used to record and analyze user behavior. To take a simple example, when you shop online, HTTP protocol is stateless. If the server wants to obtain the status of your stay on a page or what products you have viewed, a common way to do this is to store this information in cookies

2.2 How can I use cookies on the server?

This section reference: attacomsian.com/blog/cookie… The use of cookies in Boot can be viewed in this article.

1) Set cookies to be returned 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 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";
}
Copy the code

3. What is the difference between cookies and sessions? How do I use Session for authentication?

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. If some sensitive information about the Cookie is not written into the Cookie, it is best to encrypt the Cookie information and then decrypt it on the server when it is used.

So, how do you use sessions for authentication?

Most of the time we implement a specific user with a SessionID, and the SessionID is stored in Redis. For example, a user logs in successfully and returns a Cookie with a SessionID to the client. When the user sends a request to the backend, the user will bring the SessionID with it, so that the backend will know your identity status. The more detailed process of this authentication is as follows:

  1. A user sends a user name and password to the server to log in to the system.
  2. After the authentication succeeds, 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. Cookies are sent with each subsequent request when the user remains logged in.
  5. The server can compare the Session ID stored in the Cookie with the Session information stored in the memory or database to verify the user’s identity. The client responds with the current status of the user.

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

4. What is Token? JWT is what? How to authenticate based on Token?

We discussed the use of sessions to authenticate users in the last 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: Metadata describing the JWT. Defines the algorithm for generating signatures and the types of tokens.
  2. Payload: Stores the data that needs to be transmitted
  3. Signature: Indicates that the server passesPayload,HeaderAnd a key (secret) using the signature algorithm specified in the Header (HMAC SHA256 by default).

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 include JWT in the Header.
  4. The server checks the JWT and retrieves user-related information from it.

Recommended reading:

  • JWT (JSON Web Tokens) Are Better Than Session Cookies
  • JSON Web Tokens (JWT) with Sessions
  • JSON Web Token Tutorial
  • Thoroughly understand cookies, sessions, and tokens

5 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.

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

reference

  • medium.com/@sherryhsu/…
  • www.varonis.com/blog/what-i…
  • Tools.ietf.org/html/rfc674…

The public,

If you want to follow my updated articles and shared dry goods in real time, you can follow my official account.

“Java interview assault “: derived from this document designed for the interview and born of the “Java interview assault” V2.0 PDF version of the public number background reply “Java interview assault “can be free!

Necessary learning resources for Java engineers: Some Java engineers commonly use learning resources public account background reply keyword “1” can be free of routine access.