We started with KeyCloak in the last post by manually creating a Realm named Felord.cn and creating a user named Felord under it. Let’s try out the Spring Boot Adapter and see how the KeyCloak device protects Spring Boot applications.

The client

I believe that many students have used WeChat open platform, Ant open platform. First we need to register a client on one of these open platforms to obtain a set of credentials like a user name and password. Some are appid and secret; Some are called “clientid” and “secret”, which means the same thing. KeyCloak is similar and requires a Realm client to be registered with the Realm. The following figure clearly illustrates not only the relationship between a MasterRealm and a custom Realm in KeyCloak, but also the relationship between the user and the client within a Realm.

We need to create a client in the realm of Felord.cn:

After you have created it, you will notice that there is a new felord.cn client:

You can go through
http://localhost:8011/auth/realms/felord.cn/account/To log in to the created user.

Then we will edit the configuration of the spring-boot-client:

For testing purposes, I have filled in the only required redirect URI on the Settings TAB. This option means that all APIs of the SpringBoot-Client will receive permission control.

role

Role-based access control is currently the mainstream idea of access control, and KeyCloak also adopts this approach. We need to create a role and grant Felord to the user we created in the previous article. Let’s create a simple character:

keycloakThe role of the character is very powerful, and we will learn more about this concept in the next series of articles.

Roles are mapped to users

Then we assign user felord to base_user:

Now that the user, role, and role mapping are all done, it is left to define the resource on the client side.

Get and refresh the JWT

We can get the JWT pair of the user login by:

POST/auth/realms/felord. Cn/protocol/openid - connect HTTP / 1.1 / token Host: localhost: 8011 the content-type: application/x-www-form-urlencoded client_id=springboot-client&username=felord&password=123456&grant_type=password

Will get:

{" access_token ":" eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiS omit ", "expires_in:" 300, "refresh_expires_in" : 1800, "refresh_token" : "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAi omit", "token_type" : "Bearer", "not before - the policy" : 0, "session_state": "2fc7e289-c86f-4f6f-b4d3-1183a9518acc", "scope": "profile email" }

Refresh the Token by simply putting refresh_token on it and changing the grant_type to refresh_token.

POST/auth/realms/felord. Cn/protocol/openid - connect HTTP / 1.1 / token Host: localhost: 8011 the content-type: application/x-www-form-urlencoded client_id=springboot-client&grant_type=refresh_token&refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJlY WE2MThhMC05Y2UzLTQxZWMtOTZjYy04MGQ5ODVkZjJjMTIifQ.eyJleHAiOjE2MjU3NjI4ODYsImlhdCI6MTYyNTc2MTA4NiwianRpIjoiZjc2MjVmZmEtZW U3YS00MjZmLWIwYmQtOTM3MmZiM2Q4NDA5IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDExL2F1dGgvcmVhbG1zL2ZlbG9yZC5jbiIsImF1ZCI6Imh0dH A6Ly9sb2NhbGhvc3Q6ODAxMS9hdXRoL3JlYWxtcy9mZWxvcmQuY24iLCJzdWIiOiI0YzFmNWRiNS04MjU0LTQ4ZDMtYTRkYS0wY2FhZTMyOTk0OTAiLCJ0eX AiOiJSZWZyZXNoIiwiYXpwIjoic3ByaW5nYm9vdC1jbGllbnQiLCJzZXNzaW9uX3N0YXRlIjoiZDU2NmU0ODMtYzc5MS00OTliLTg2M2ItODczY2YyNjMwYW FmIiwic2NvcGUiOiJwcm9maWxlIGVtYWlsIn0.P4vWwyfGubSt182P-vcyMdKvJfvwKYr1nUlOYBWzQks

Note: two requests
content-typeAre all
application/x-www-form-urlencoded.

Spring Boot client

Create a traditional Spring Cloak application with the Spring MVC module and add the KeyCloak starter:

<dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-spring-boot-starter</artifactId> The < version > 14.0.0 < / version > < / dependency >

The current
keycloakVersion is
14.0.0

Then write a random Spring MVC interface:

/** * @author felord.cn * @since 2021/7/7 17:05 */ @RestController @RequestMapping("/foo") public class FooController { @GetMapping("/bar") public String bar(){ return "felord.cn"; }}

Next, we declare that only users with the base_user role in Felord.cnRealm can access the /foo/bar interface. So what’s the definition? We will first define it statically in Application.yml in Spring Boot and then implement dynamic control. The configuration is as follows:

Realm: Felord.cn # KeyCloak: Realm: Felord.cn # KeyCloak: Realm: Felord.cn # http://localhost:8011/auth # client name resource: springboot - client # statement this is a public client, otherwise cannot be used in keycloak external environment, the public - 403 client: True # Configure the client's security constraints, which are the roles that map the resource security-constraints: # Role and resource mapping. /foo/ bar-auth-roles: -base_user security-collections: -patterns: - '/foo/bar'

Then start Spring Boot application and call in the browser, http://localhost:8080/foo/bar, you will find that the browser will jump to the following address:

http://localhost:8011/auth/realms/felord.cn/protocol/openid-connect/auth?response_type=code&client_id=springboot-client& redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Ffoo%2Fbar&state=20e0958d-a7a9-422a-881f-cbd8f25d7842&login=true&scope=openi d

It is based on OIDC(enhanced version of OAuth 2.0) authentication authorization mode. /foo/bar will respond correctly only if you fill in the username and password correctly.

conclusion

Please note: this is a series of articles, so please click at the beginning of this article
#keycloakView existing chapters.

We implemented OIDC authorization with only a few configurations and secured the interface in Spring Boot, which was pretty simple. However, after reading this article, you will have many questions, because you do not understand the OIDC protocol. This protocol is very important, big factories are using it. The next article will give you a refresher on this agreement. The DEMO of this article has been uploaded to Git, you can follow the public account: code farm Xiaopang man reply to keycloak3 to get the DEMO. More thumb up, see again, forward, comment, have a meal is just the power of pangge’s creation and sharing.

Follow the official account: Felordcn for more information

Personal blog: https://felord.cn