Spring boot (4) uses JWT and spring security to protect the rest API
Under normal circumstances, it is very risky to directly expose the API. If you are directly attacked by a machine, you can drink a pot. Generally speaking, the API should be divided into certain permission levels, and then a user should be authenticated. The corresponding API should be opened to the user according to the authentication results. At present, there are several mainstream schemes:
The first one is not introduced. Since it relies on session to maintain status, it is not suitable for the mobile era. New projects should not be adopted. The second OAuth scheme and JWT are based on token, but OAuth is actually too complex for companies that do not make open platforms. We mainly introduce the third kind: JWT.
What is JWT?
JWT is the abbreviation of JSON web token. It is a compact and self-contained JSON object that can be safely transmitted based on RFC 7519 standard. Because the data is digitally signed, it is trusted and secure. JWT can use HMAC algorithm to encrypt secret or RSA's public and private key pair to sign.
Workflow of JWT
The following is a workflow diagram of JWT. Simulate the actual process as follows (assuming that the protected API is in / protected)
JWT workflow diagram
In order to better understand what this token is, let's first look at what a token looks like after it is generated. The following mess is it.
eyJhbGciOiJIUzUxMiJ9. eyJzdWIiOiJ3YW5nIiwiY3JlYXRlZCI6MTQ4OTA3OTk4MTM5MywiZXhwIjoxNDg5Njg0NzgxfQ. RC-BYCe_ Uz2urtwddupwxip4nmsoeq2o6uf-8tvplqxy1-ci9u1-a-9daajgfnwkhe81mpnr3gxzfrbab3wuag, but if you look carefully, you can still see that the token is divided into three parts, each part is used Separated, each segment is encoded with Base64. If we use a Base64 decoder( https://www.base64decode.org/ ), you can see that the first part eyjhbgcioijiuzuxmij9 is parsed into:
In order to simplify our work, we introduce a relatively mature JWT class library called jjwt( https://github.com/jwtk/jjwt )。 This class library can be used to generate and verify JWT tokens for Java and Android.
Spring security is a general security framework based on spring. There are too many contents in it. The main purpose of this paper is not to talk about this framework, but how to use spring security and JWT to complete API protection. Therefore, please go to the official website to learn about the basic content or expanded content of spring security( http://projects.spring.io/spring-security/ )。
Now after starting the service, access http://localhost:8090 You can see that the root directory is still displayed normally
But let's try http://localhost:8090/users , take a look at the console, and we will see the following output, which tells us that our access is denied because the user is not authenticated.
Code of this chapter: https://github.com/wpcfan/spring-boot-tut/tree/chap04