spring - Keycloak 与 Spring boot - 如何应用资源范围

标签 spring spring-boot keycloak

我使用 Keycloak 7.0.1 和 Spring Boot 1.5.16.RELEASE 通过指定资源、基于角色的策略和权限来保护端点 - 这按预期工作。

棘手的事情是仅保护 POST 并允许对某个特定 URI 进行 GET 请求。我在 application.yml 中做了什么:

policy-enforcer-config:
  enforcement-mode: ENFORCING
  paths[0]:
    name: all
    path: /*
  paths[1]:
    name: test post
  path: /my/url
    methods[0]:
      method: GET
      scopes[0]: view
    methods[1]:
      method: POST
      scopes[0]: edit

在 keyclaok 中,我创建了 editview 范围、/my/url 资源、具有角色和否定决策的策略(如果用户具有该角色 - 拒绝访问),权限包含资源、范围和策略。评估按预期进行,但我的 Spring 应用程序总是收到 403 错误。

您能否为我提供一个资源范围使用的示例,或者建议我还需要做什么才能使其正常工作?

最佳答案

可能有多个问题,但首先,检查您的 SecurityConfig。

这就是我们现有的:

@Configuration
@EnableWebSecurity
@KeycloakConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(KeycloakSpringBootProperties.class)
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    bla-bla..

@Override
public void configure(WebSecurity web) throws Exception {
    web
            .ignoring()
            .antMatchers(HttpMethod.POST, "/auth/**")
            .antMatchers(HttpMethod.OPTIONS,"/**")
            // allow anonymous resource requests
            .and()
            .ignoring()
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js",
                    "/actuator/**"

            )
    ;
}


    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            .exceptionHandling()
            .defaultAuthenticationEntryPointFor(
                    getRestAuthenticationEntryPoint(),
                    new AntPathRequestMatcher("/**")
            )
            .authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()

            .authorizeRequests()

            // system state endpoint
            .antMatchers("/ping").permitAll()

            .antMatchers(HttpMethod.GET, "/whatever/you/need/to/open/to/public/one", "/whatever/you/need/to/open/to/public/two").permitAll()


            // User authentication actions
            .antMatchers("/auth/**").permitAll()
            .antMatchers("/**/*.css").permitAll()

            .anyRequest().authenticated()
    ;

    http
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
    ;

    // disable page caching
    http
            .headers()
            .frameOptions().sameOrigin()
            .cacheControl();

}

如果您想使用角色限制 REST API 端点,请为您的 Controller 方法添加 @PreAuthorize("hasRole('your.role.from.keycloak')")

关于spring - Keycloak 与 Spring boot - 如何应用资源范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58727765/

相关文章:

java - 实现Spring Service根据配置向不同的Kafka主题发送消息

java - 无法使用适用于 Java 的 Azure 管理库在订阅中列出 azure 应用程序服务(Spring Boot 应用程序)

java - 如何在 Spring Boot 中的 JWT 中发送经过身份验证的用户 ID?

authentication - Keycloak - 如何允许无需注册即可链接帐户

docker - 带有副本的Keycloak和Docker Swarm重定向循环

java - Mockito 使用时抛出 NPE

Spring boot OAuth成功登录监听器未触发

java - 为 play 框架和 spring 定制 secureSocial(依赖注入(inject))

Keycloak:Admin-cli 添加 SMTP 服务器详细信息?

java - Spring-data-elasticsearch “nested query throws [nested] failed to find nested object under path”异常