【问题标题】:Using spring security annotations with keycloak使用带有 keycloak 的 spring 安全注释
【发布时间】:2016-04-05 18:17:25
【问题描述】:

我只是 Spring Security 的初学者,但我想知道是否可以以我可以使用 @PreAuthorize@PostAuthorize@Secured 和其他注释的方式配置 keycloak。 例如,我在简单的 Spring Rest webapp 中配置了 keycloak-spring-security-adapter 和 Spring Security,以便我可以访问控制器中的 Principal 对象,如下所示:

@RestController
public class TMSRestController {

     @RequestMapping("/greeting")
     public Greeting greeting(Principal principal, @RequestParam(value="name") String name) {
        return new Greeting(String.format(template, name));
     }
...
}

但是当我尝试这个时(只是一个例子,实际上我想在授权之前执行自定义 EL 表达式):

@RestController
public class TMSRestController {

    @RequestMapping("/greeting")
    @PreAuthorize("hasRole('ADMIN')")
    public Greeting greeting(Principal principal, @RequestParam(value="name") String name) {
        return new Greeting(String.format(template, name));
    }
...
}

我得到异常:

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:在 SecurityContext 中找不到 Authentication 对象

在我的 spring 安全配置中,我启用了全局方法安全性:

我需要什么才能使这个 Spring 安全注释起作用?是否可以在这种情况下使用这个注解?

【问题讨论】:

    标签: spring spring-security keycloak pre-authentication


    【解决方案1】:

    您仍然需要使用 Keycloak 配置 Spring Security。查看adapter documentation 以获取基于注释的配置。设置好之后,您的 Spring Security 注释将适用于授权调用。

    【讨论】:

    • 答案是前一段时间的,但我遇到了与 Spring Security 和 Keycloak 类似的问题。在我的 Spring Boot 应用程序中,我配置了适配器,但无法使用 @PreAuthorize("hasAuthority('user')")。如果发送了请求,则注释无效。我现在通过在我的安全配置中添加 @EnableGlobalMethodSecurity(prePostEnabled = true) 来修复它。
    • 感谢 prePostEnabled=true !
    • 截至今天 (12/18/19),您提供的适配器文档的链接不再存在 (404)。
    【解决方案2】:

    这里是示例代码:

    @EnableWebSecurity
    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true,
                            securedEnabled = true,
                            jsr250Enabled = true)
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
    public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
     }
    

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    

    除了这段代码。您需要为领域角色和客户端(应用程序角色)进行角色映射。应用程序角色将被放入@PreAuthorize

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2022-09-28
      • 2011-02-23
      • 2015-06-04
      • 2019-10-09
      • 2013-08-08
      相关资源
      最近更新 更多