Joke Collection Website - Blessing messages - Single sign-on JWT and Spring Security OAuth

Single sign-on JWT and Spring Security OAuth

By combining JWT with Spring Security OAuth2, you can avoid remotely dispatching authentication and authorization services for each request. The resource server only needs to authenticate from the authorization server once and return JWT. The returned JWT contains all information of the user, including permission information.

1. What is JWT?

JSON Web Token(JWT) is an open standard (RFC 75 19). JWT defines a compact and self-contained standard, which aims to package information from various topics into JSON objects. Subject information is encrypted and verified by digital signature. HMAC algorithm or RSA (asymmetric public/private key encryption) algorithm is often used for JWT signature, which has high security.

2. The structure of 2.JWT

The structure of JWT consists of three parts: header, payload and signature. So the usual format of JWT is xxxxx.yyyyy.zzzzz

2. 1. Header

The header usually consists of two parts: the token type (namely JWT) and the algorithm type used, such as HMAC, SHA256 and RSA. For example:

Using Base64 as the first part of JWT, it is not recommended to put sensitive information in the header of JWT.

2.2 Payload

The following is an example of the payload section:

As the second part of JWT, it is not recommended to put sensitive information in the payload of JWT.

2.3.Signature

To create the signature part, you need to encrypt the Base64 encoded header and payload with a key. The formula of the encryption algorithm is as follows:

Signature can be used to verify whether the message has been changed during delivery. For a token signed with a private key, it can also verify whether the sender of JWT is who it says it is.

3. How does 3.JWT work

After the client obtains JWT, for each subsequent request, it is no longer necessary to judge the requesting user and the user's authority through the authorization service. In micro-service system, single sign-on can be realized by using JWT. The authentication flow chart is as follows:

4. Case engineering structure

Schematic diagram of engineering principle is as follows:

5. Build an authorization service authorization service.

UserServiceDetail.java

UserRepository.java

Entity class users need to implement the UserDetails interface, and entity class roles need to implement the GrantedAuthority interface.

User.java

Role.java

Jks file generation needs to use Java keytool tool to ensure that Java environment variables are ok. Enter the following command:

Where -alias option is an alias, -keyalg is an encryption algorithm, -keypass and -storepass are password options, -keystore is the file name of jks, and -validity is the expiration time of the configured jks file (unit: days).

The generated jks file is used as a private key, which is only allowed to be held by authorized services and used to generate JWT through encryption. Just put the generated jks file in the src/main/resource directory of auth-service module.

For resource services such as user services, JKT needs to be decrypted using the public key of jks. The command to obtain the public key of jks file is as follows:

This command requires installing the openSSL download address, and then manually configuring the installation directory of openssl.exe into the environment variable.

After entering the password fzp 123, a lot of information will be displayed. Just extract the public key, as shown below:

Create a new public.cert file, copy the above public key information into the public.cert file and save it. And put the file in the src/main/resources directory of resource services (such as user-service). At this point, auth-service has been established.

Maven may compile the jks file when compiling the project, resulting in the garbled jks file, which will eventually be unusable. You need to add the following to the pom.xml file:

6. Building user service resource services

Inject a Bean of type JwtTokenStore, initialize JWT converter JwtAccessTokenConverter, and set the public key used to decrypt JWT.

To configure authentication management of resource services, all interfaces need to be authenticated except those used for registration and login.

Create a new configuration class GlobalMethodSecurityConfig, and open method-level security verification through the annotation @EnableGlobalMethodSecurity.

Copy the users, roles and user repositories of the Authorized Services module to the module. Write a method to insert a user in the userService of the service layer, and the code is as follows:

Configure the tool class BPwdEncoderUtil for user password encryption:

Implement an API interface/user/registration for user registration. The code is as follows:

Add a login () method in the userServicedetail of the service layer, and the code is as follows:

AuthServiceClient, as a pretend client, obtains JWT by calling auth-serviceinterface/oauth/token remotely. In the API interface of request /oauth/token, authorization information, authentication type (grant_type), username (username) and password need to be passed into the request header. The code is as follows:

Among them, AuthServiceHystrix is the fuse of AuthServiceClient, and the code is as follows:

JWT contains access_token, token_type, refresh_token and other information, and the code is as follows:

UserLoginDTO contains user and JWT member attributes, which are used to return the entity of data:

Login exception class UserLoginException

Global exception handling part class ExceptionHandle

Add a login API interface /user/login in the UserController class of the Web tier, as shown below:

Start three services: Eureka service, authorization service and user service.

7. Use postman to test

Access was denied due to lack of permission. Manually add the ROLE_ADMIN permission in the database and associate it with the user. Log in again and get JWT, and then request the /user/foo interface again.

In this case, the user obtains the encrypted JWT of the authorized service through the login interface. After users successfully obtain JWT, they need to carry JWT with them in every request to access resource services in the future. The resource service decrypts JWT through the public key. After successful decryption, user information and authority information can be obtained, so as to judge who the user corresponding to JWT is and what authority he has.

Once a token is obtained and used many times, the resource service will no longer access the user information and user rights information corresponding to the token every time.

Once the user information or permission information changes, the relevant information stored in the token has not changed, and you need to log in again to get a new token. Even if the token is regained, it can still be used if the original token has not expired. An improved method is to cache the obtained token in the gateway after successful login. If the user's permissions change, delete the cached token on the gateway. When the request passes through the gateway, it is judged whether the requested token exists in the cache, and if not, the user is prompted to log in again.