background

The concept of OAuth2 is not described here, but if you are interested, you can check out my other related articles. Here you can directly demonstrate the four authorization methods of OAuth2, using posture

1 Authorization-Code

1.1 access to obtain access to the authentication server authorization code apis, such as: localhost: 7777 / request/the authorize? Client_id = cms&Response _type=code Then we jump to the authentication server login address

Here through the authentication server pre-issued account/key, login into the authorization pageCopy the code

After clicking authorization/the authentication server will redirect the address, here you can get our authorization code, as shown in code=taApM1Copy the code

1.2 Accessing a Token Using authorization Code =taApM1 The following figure shows how to obtain an Access_token from the API

1.3 we can also through authentication server access_token check the API to check whether we get access_token http://localhost:7777/oauth/check_token? effectively token=474f802c-d65c-4e64-aaf2-dfdf034c807c

PS: In the access_token, there is a refresh_token message. If you are interested, you can refer to my other article, which has a description of the function of refresh_token And refresh_token] (https://juejin.cn/post/7056614367747375118)Copy the code

1.4 Access the resource address we need to access by using the Access_token demo URL

2. Implicit

2.1 On the basis of the authorization code mode, the process of obtaining the authorization code is directly removed, which is equivalent to directly obtaining the access_token and accessing the target address. Configure the redirection URL on the authentication server first:

public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter { ``` @Override public void Configure (ClientDetailsServiceConfigurer clients) throws the Exception {/ / use the memory storage clients inMemory () withClient (CLIENT_ID) Secret (passwordencoder.encode (SECRET_CHAR_SEQUENCE)) // Client security code.autoapprove (false) // Return code for direct automatic authorization success if true . RedirectUris (" http://localhost:7778/resource_server ") / / redirect uri, Scopes ("app", "file", "zone") // Allow the scope of authorization, ALL / /. You won't get authorization page accessTokenValiditySeconds (ACCESS_TOKEN_VALIDITY_SECONDS) / / / / token time seconds . RefreshTokenValiditySeconds (REFRESH_TOKEN_VALIDITY_SECONDS) / / refresh token only seconds while authorizedGrantTypes (GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT); // Allow authorization type}}Copy the code

2.2 direct access to obtain access_token API address localhost: 7777 / request/the authorize? response_type=token&client_id=cms&redirect_uri=http://localhost:7778/resource_serverSo redirect_URI is your target access address and you can see how it’s going to be accessed or it’s going to go to the authentication server login page, login and then authorization

After the authorized Will jump straight to our redirect_uri = http://localhost:7778/resource_server this address, and carried to obtain access_token, as shown in figureCopy the code

2.3 Verify the validity of the Access_token obtained in Step 2.2

3 Password (Password)

If you have a high level of trust in an application, allow users to give their username and password directly to the application. The application uses your password to request a token, called password/for example, your own authenticated serverCopy the code

3.1 Preparations The authentication center supports password authorization

public class OAuth2Configuration extendsAuthorizationServerConfigurerAdapter { @Override public void Configure (ClientDetailsServiceConfigurer clients) throws the Exception {/ / configure password authorization model. And (). WithClient (" cms1 ") .authorizedGrantTypes("password", Scopes ("select").scopes(" oauth2") // user --> BCryptPasswordEncoder generated by encryption algorithm .secret("$2a$10$vrRjc8vlDwv6gBHlv/me8eeRsHO7P3I7ge0F03sr4C3hh/SmS/lMC"); } public static void main(String[] args) { String pass = "user"; BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); final String passHash = encoder.encode(pass); System.out.println(passHash); final boolean matches = encoder.matches(pass, passHash); System.out.println(matches); } // $2a$10$jbVRxqHjW8QIYw7.UFVD/Ocf.7TSKLhZrGJRouTKq/PyTNTQ6TVIa // true Please note that my secret configuration (" $2 a $10 $vrRjc8vlDwv6gBHlv/me8eeRsHO7P3I7ge0F03sr4C3hh/SmS/lMC ") because I choose is BCryptPasswordEncoder encryption After the original password user corresponding encryption is $2 a $10 $vrRjc8vlDwv6gBHlv me8eeRsHO7P3I7ge0F03sr4C3hh/SmS/lMCCopy the code

3.2 Accessing the Authentication Center in Password Mode Obtaining the Access_token API Addresshttp://localhost:7777/oauth/token?username=user&password=user&grant_type=password&scope=select&client_id=cms1&client_sec ret=userGet the access_token

3.3 Finally, verify the access_token we obtained through password mode to see whether it is validhttp://localhost:7777/oauth/check_token?token=5691ce5f-686b-40a6-9832-88810792be7fEffective/successful

4 Client Credentials

The Client Credentials Grant allows clients to authenticate to the service provider in their own name, not the user's. Strictly speaking, the client-side pattern is not the problem that the OAuth framework addresses. In this model, users register directly with the client, and the client requests services from the "service provider" in its own name, with no authorization issues.Copy the code

4.1 Preparations The authentication center is configured to support client credentials

public class OAuth2Configuration extendsAuthorizationServerConfigurerAdapter { @Override public void Configure (ClientDetailsServiceConfigurer clients) throws the Exception {/ / configure the client authorization model. And (). WithClient (" client_1 ") .authorizedGrantTypes("client_credentials", "refresh_token") .scopes("select") .authorities("oauth2") .secret("$2a$10$vrRjc8vlDwv6gBHlv/me8eeRsHO7P3I7ge0F03sr4C3hh/SmS/lMC"); // Secret is encrypted by the user as in step 3.1}Copy the code

4.2 access authentication center for access_token API address http://localhost:7777/oauth/token? grant_type=client_credentials&scope=select&client_id=client_1&client_secret=user

4.3 verify whether we get access_token http://localhost:7777/oauth/check_token? effectively Token = 2AB79CBF-4809-4d90-a68d-fd78de17CB4D Valid/successful

Download the source code

Demo source code demo download