通过 Keycloak 保护个人资源免受 Spring 引导

Protect individual resources from Spring Boot via Keycloak

我有一个非常简单的 Spring 启动应用程序,其资源位于 /repositories/persons

这是我的 build.gradle 文件。

plugins {
    id 'org.springframework.boot' version '2.4.0'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}

// use java 11 until keycloak is fixed
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencyManagement {
    imports {
        mavenBom "org.keycloak.bom:keycloak-adapter-bom:12.0.1"
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.keycloak:keycloak-spring-boot-starter'

    implementation 'org.flywaydb:flyway-core'
    runtime 'org.postgresql:postgresql'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

...
...

这是我的 SecurityConfig.java 文件。

@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    var keycloakAuthenticationProvider = keycloakAuthenticationProvider();
    keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
    auth.authenticationProvider(keycloakAuthenticationProvider);
  }

  @Bean
  @Override
  protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
    return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.authorizeRequests()
        .antMatchers("/persons*")
        .hasRole("user")
        .anyRequest()
        .permitAll();
  }

  @Bean
  public KeycloakConfigResolver keycloakConfigResolver() {
    return new KeycloakSpringBootConfigResolver();
  }
}

这是我的 application.yaml 文件。

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    username: john
    password: john

keycloak:
  auth-server-url: http://localhost:8081/auth/
  realm: myrealm
  resource: myclient
  credentials:
    secret: 45d43bd6-5ab9-476c-83c8-67bd203a78ee

这一切都在我的本地机器上,Keycloak 和 Postgres 是通过 docker compose 启动的。


version: "3.1"

volumes:
  postgres_data:
      driver: local

services:
  db:
    image: "postgres:13.1"
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: postgres
      POSTGRES_USER: john
      POSTGRES_PASSWORD: john
  postgres:
    image: "postgres:13.1"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: password
  keycloak:
    image: quay.io/keycloak/keycloak:12.0.1
    environment:
      DB_VENDOR: POSTGRES
      DB_ADDR: postgres
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_SCHEMA: public
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: Pa55w0rd
    ports:
      - 8081:8080
    depends_on:
      - postgres

我在 Keycloak 中有用户 zemircoone,他们都有 user 角色。一切都很好,路线 /persons 受到保护,而 /repositories 对所有人开放。

这是我的问题!我想保护个人资源,例如/person/1。我无法让它工作 :( 我已经尝试了好几天了,但没有成功。这是我的 keycloak 设置。

这是我的政策。

这是资源。

这是权限。

在 Keycloak 的评估过程中,这一切都有效。但是,它不能直接在我的 Spring 启动应用程序中运行。我仍然可以以 zemirco 的身份访问 /person/1,尽管用户 one 应该只有访问权限。

此刻我有点迷茫。你有什么想法吗?

非常感谢!


编辑 2021 年 1 月 10 日

谢谢大家的回答,但我仍然认为它是可行的,我这边(应用程序方面)不需要付出很多额外的努力。我特别关注政策执行者 https://www.keycloak.org/docs/latest/authorization_services/#_enforcer_overview.

A PEP is responsible for enforcing access decisions from the Keycloak server where these decisions are taken by evaluating the policies associated with a protected resource. It acts as a filter or interceptor in your application in order to check whether or not a particular request to a protected resource can be fulfilled based on the permissions granted by these decisions.

这听起来和我想做的一模一样。不幸的是我不能让它工作。我只是认为我的配置是错误的或者可能不完整。我会为这个问题添加赏金。

Keycloak 以在访问管理解决方案中拥有最差的 policy/access 工具而闻名,但是,您描述的问题似乎有点奇怪。

Keycloak 是一种访问管理工具,从策略的角度来看,它提供决策,但不强制执行,因此由于策略评估按预期工作,您需要做的就是做出 api 从您的 spring 应用调用评估点,如果它是 200 那么用户将访问,如果不是则不显示该页面。

另一种解决方案是使用预制策略执行点,apache/nginx spring 都有自己的自定义策略执行点。

一些有用的链接:

how-to-use-keycloak-policy-enforcer-with-spring-boot-application

keycloak-enforcement-filter

Keycloak 中的 AuthZ 是 PITA,恕我直言,不应该使用它。有更好的解决方案(例如 OPA)。只是遵循原则:“不要做傻事!”

其次,不要混淆 AuthN 和 AuthZ。 仅仅因为在 Keycloak 中配置了一些 AuthZ 策略,这并不意味着它们被“自动和神奇地”使用。 如果您使用任何适配器(无论 Spring Security 还是某些 KC 自己的适配器)进行身份验证,它们都在做“仅 OIDC”,而 OIDC 是关于 AuthN,而不是 AuthZ。

如果您想在您的应用程序中调整或使用您的 AuthZ 策略和规则,您必须将它们与身份验证分开查询。 Keycloak 为此提供了 keycloak-authz-client,记录在此处:https://www.keycloak.org/docs/latest/authorization_services/#_service_client_api

终于成功了:)我很高兴!

这是我所做的。

首先,我使用了我的 Keycloak 客户端安装中的 keycloak.json 文件。一开始我试图将所有配置放入我的application.yamlkeycloak.json 文件必须位于 src/main/webapp/WEB-INF/keycloak.json。当您使用 JSON 文件而不是 YAML 文件时,您可以从 SecurityConfig.

中删除以下内容
public KeycloakConfigResolver keycloakConfigResolver() {
  return new KeycloakSpringBootConfigResolver();
}

其实挺好看的。您只需将 Keycloak 中的内容复制并粘贴到文件中,即可确保一切正确。我看到的另一个问题是,与 application.yaml 中的 policy-enforcer-config 相比,keycloak.json 中的配置被称为 policy-enforcer。这很烦人,因为我一开始没有意识到这一点。这是配置。

{
  "realm": "myrealm",
  "auth-server-url": "http://localhost:8081/auth/",
  "ssl-required": "external",
  "resource": "myclient",
  "verify-token-audience": true,
  "credentials": {
    "secret": "45d43bd6-5ab9-476c-83c8-67bd203a78ee"
  },
  "confidential-port": 0,
  "policy-enforcer": {}
}

"policy-enforcer": {} 是最重要的部分。在这里我们启用默认设置并简单地说Keycloak应该授权对我们资源的所有请求。

然后似乎一切正常。我只能通过正确的用户访问受保护的资源。但是,在我注销并再次尝试访问该资源后,我仍然能够做到这一点。在这里,我了解到我的蚂蚁匹配器是错误的。这是正确的配置。

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.authorizeRequests()
        .antMatchers("/persons/**") // changed from .antMatchers("/persons*")
        .hasRole("user")
        .anyRequest()
        .permitAll()
        .and()
        // this is just to have a convenient GET /logout method. DO NOT USE IN PRODUCTION
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
  }

现在一切正常,Keycloak 中的 resources/policies/permissions 自动应用到我的 Spring 启动应用程序中。