3

We on a initially tried keycloak , manually create a program called felord.cn of realm and the realm built named under felord users. try the corresponding 160f0e82b1dc29 Spring Boot Adapter and see how keycloak protects the Spring Boot application.

Client

I believe many students have used WeChat open platform and Ant open platform. First, we need to register a client on these open platforms to obtain a set of credentials similar to a username and password. Some are called appid and secret ; some are called clientid and secret , both have the same meaning. In fact, keycloak is similar, and a client realm 160f0e82b1dd03. The following figure illustrates clearly not keycloak in Master The realm and custom The realm relationship, also described in a The realm relationship between the user and the client.

Realm、client、user关系图

We need to create a client felord.cn this realm

在realm中创建客户端

After creation, you will find that felord.cn is one more client for 060f0e82b1ddac:

realm的客户端列表

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

Then we edit and configure the spring-boot-client

填写重定向URL

For testing, here I only fill in the only required item valid redirection URI in the settings tab. This option means that springboot-client will receive permission control.

Character

Role-based permission control is the current mainstream permission control idea, keycloak also adopts this method. We need to create a role and grant felord created in the previous article. Let's create a simple character:

在keycloak中创建角色

keycloak a very powerful role function. In the following series of articles, Fat Brother will learn this concept in depth with you.

Role mapping to user

Then we assign the role base_user created above to the user felord :

给realm中的用户赋予角色

Now that the user, role, and role mapping are all done, the only thing left is to define resources on the client.

Get and refresh JWT

We can get the JWT pair logged in by the user in the following way:

POST /auth/realms/felord.cn/protocol/openid-connect/token HTTP/1.1
Host: localhost:8011
Content-Type: application/x-www-form-urlencoded

client_id=springboot-client&username=felord&password=123456&grant_type=password

Will get:

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

To refresh the token, you only need to bring refresh_token and change grant_type to refresh_token to refresh the token. Right, the following is the message requesting refresh:

POST /auth/realms/felord.cn/protocol/openid-connect/token HTTP/1.1
Host: localhost:8011
Content-Type: application/x-www-form-urlencoded

client_id=springboot-client&grant_type=refresh_token&refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJlYWE2MThhMC05Y2UzLTQxZWMtOTZjYy04MGQ5ODVkZjJjMTIifQ.eyJleHAiOjE2MjU3NjI4ODYsImlhdCI6MTYyNTc2MTA4NiwianRpIjoiZjc2MjVmZmEtZWU3YS00MjZmLWIwYmQtOTM3MmZiM2Q4NDA5IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDExL2F1dGgvcmVhbG1zL2ZlbG9yZC5jbiIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODAxMS9hdXRoL3JlYWxtcy9mZWxvcmQuY24iLCJzdWIiOiI0YzFmNWRiNS04MjU0LTQ4ZDMtYTRkYS0wY2FhZTMyOTk0OTAiLCJ0eXAiOiJSZWZyZXNoIiwiYXpwIjoic3ByaW5nYm9vdC1jbGllbnQiLCJzZXNzaW9uX3N0YXRlIjoiZDU2NmU0ODMtYzc5MS00OTliLTg2M2ItODczY2YyNjMwYWFmIiwic2NvcGUiOiJwcm9maWxlIGVtYWlsIn0.P4vWwyfGubSt182P-vcyMdKvJfvwKYr1nUlOYBWzQks
Note: Both requests of content-type are application/x-www-form-urlencoded .

Spring Boot client

Build a very traditional Spring Boot application, don’t forget to bring Spring MVC module, and then add keycloak starter

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

Then just write a 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 felord.cn realm can access the /foo/bar interface. So where is the definition? We first in 160f0e82b1e3fc spring boot , and application.yml we will implement dynamic control. The configuration is as follows:

keycloak:
# 声明客户端所在的realm
  realm: felord.cn
# keycloak授权服务器的地址
  auth-server-url: http://localhost:8011/auth
# 客户端名称
  resource: springboot-client
# 声明这是一个公开的客户端,否则不能在keycloak外部环境使用,会403
  public-client: true
# 这里就是配置客户端的安全约束,就是那些角色映射那些资源
  security-constraints:
# 角色和资源的映射关系。下面是多对多的配置方式 ,这里只配置base_user才能访问 /foo/bar
    - auth-roles:
        - base_user
      security-collections:
        - patterns:
            - '/foo/bar'

Then start the Spring Boot application and call http://localhost:8080/foo/bar in the browser, 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=openid

OIDC认证授权登录

It is based on the OIDC (enhanced version of OAuth 2.0) authentication and authorization mode. Only if you fill in the username and password correctly can you get the correct response /foo/bar

to sum up

Please note: This is a series of articles, please click #keycloak view the existing chapters.

We only did some configuration to achieve OIDC authentication and authorization, and protect the interface in Spring Boot. This is really simple. But after reading this article, you will have a lot of questions, because you don't know much about the OIDC protocol. This agreement is very important, and big factories are using it. The next article will give you supplementary lessons for this agreement. The DEMO of this article has been uploaded to Git, you can follow the public : 160f0e82b1ecb8 code farmer small fat brother reply keycloak3 get the DEMO. Like a lot, read again, forward, comment, is the driving force for fat brother to create and share.

Follow the public account: Felordcn for more information

personal blog: https://felord.cn


码农小胖哥
3.8k 声望8k 粉丝