当前位置: 首页 > 知识库问答 >
问题:

使用spring boot(安全性)和KeyCloak启用角色身份验证?

满勇军
2023-03-14

我在试着做一件简单的事。

接下来是设置我的keycloak信息(realm,role,user)https://medium.com/@bcarunmail/securing-rest-api-using-keycloak-and-spring-oauth2-6ddf3a1efcc2

所以,

我基本上用一个客户机、一个具有特定角色“user”的用户来设置我的keycloak,并像这样配置它:

@Configuration
@KeycloakConfiguration
//@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConf extends KeycloakWebSecurityConfigurerAdapter
{
    /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

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

    @Bean
    public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
            KeycloakAuthenticationProcessingFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
            KeycloakPreAuthActionsFilter filter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }


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

    }
}
.anyRequest().permitAll();

但当我把这作为最后一条规则

 .anyRequest().denyAll();

我总是得到403。

我发现了这个:

f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication
o.k.a.BearerTokenRequestAuthenticator    : Found [1] values in authorization header, selecting the first value for Bearer.
o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
o.k.a.BearerTokenRequestAuthenticator    : successful authorized
a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: [] 
o.k.adapters.RequestAuthenticator        : User 'testuser' invoking 'http://localhost:9090/api/user/123' on client 'users'
o.k.adapters.RequestAuthenticator        : Bearer AUTHENTICATED
f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED
o.s.s.authentication.ProviderManager     : Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
o.s.s.core.session.SessionRegistryImpl   : Registering session 5B871A0E2AF55B70DC8E3B7436D79333, for principal testuser
f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@355f68d6: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@5d7a32a9; Not granted any authorities
[nio-9090-exec-3] o.s.security.web.FilterChainProxy        : /api/user/123 at position 8 of 15 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
[nio-9090-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>6.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-security-adapter</artifactId>
            <version>6.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

我请求访问令牌发送:

client_id -> my client from keycloak
username -> my user from keycloak
password -> my password from keycloak
grant_type -> password
client_secret -> from keycloak

我得到一个令牌,然后我用它来请求我的应用程序EndoInt。无论我使用什么endpoint(角色用户endpoint或角色管理员endpoint),我的请求总是有效的。

在我的房产中,我有这样的东西:

keycloak:
  auth-server-url: http://localhost:8080/auth/
  resource: users-api
  credentials:
    secret : my-secret
  use-resource-role-mappings : true
  realm: my-realm
  realmKey:  my-key
  public-client: true
  principal-attribute: preferred_username
  bearer-only: true

你知道如何在这种情况下实际启用这些角色吗?

我必须配置客户端才能使用JWT吗?有什么想法吗?

@Secured("admin")
@PreAuthorize("hasAnyAuthority('admin')")
"realm_access": {
    "roles": [
      "offline_access",
      "admin",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },

共有1个答案

奚卓
2023-03-14

调试堆栈中:我看到您正在调用/api/user/123,而在您的安全配置中,您正在保护/user/*,这是不一样的,将您的安全性更改为:

.antMatchers("/api/user/*").hasRole("user")
                .antMatchers("/api/admin*").hasRole("admin")

P.S:您不需要注册KeycloakAuthenticationProcessingFilterKeycloakPreAuthActionsFilter

 类似资料:
  • 但是该实现假设身份验证也是通过存储在数据库中的密码(@Password注释)完成的。我们希望根据LDAP对用户进行身份验证,然后根据存储在数据库中的内容分配角色。 是否有可用的教程/拦截器?我为每一个输入感到高兴? PS:quarkus安全ldap扩展不是解决方案,因为它假设角色也存储在ldap中。

  • 我正在尝试通过连接到LDAP使用Spring Security进行我的第一个演示。 我使用的Sping版本是:3.1.0.RELEASE 以下是我的security-integration.xml: 然而,每当我部署我的战争时,我都会遇到这个例外: HTTP状态500 - 类型异常报告 消息 描述服务器遇到一个内部错误(),该错误阻止它完成此请求。 例外情况 javax.servlet。Servl

  • 我正在开发REST webService,我的一些客户机将使用我的webservices,所以为了识别真正的客户机,我决定给每个真正的客户机一个唯一的应用程序令牌。客户机将对这个令牌进行编码,他们将把这个令牌放在请求头中,我已经在我的REST webservices中配置了一个REST过滤器来验证令牌。我不想使用https。我的问题是,任何人都可以从我的客户端站点获取该令牌,并可以使用我的REST

  • 我在学Spring保安。 在浏览了一些教程之后,我发现其中一些使用了UserRole,而一些使用了一个实现身份验证的UserAuthentication类。我尝试实现的一个(并起作用)是创建一个自定义的MyUserDetailsService,它实现UserDetailsService,并授予权限(角色?)像这样: 我想知道用户角色和GrantedAuthorities之间有什么区别(例如,当使用

  • 我试图为AWS实现“开发人员身份验证身份”,如下所示:https://AWS.amazon.com/blogs/mobile/amazon-cognito-innecling-developer-authenticated-identities/ 我很好地理解了基本流程。 我怎样才能做到这一点?

  • 在过去的几周里,我一直在努力掌握KeyClope,这样我就可以实现一种使用遗留提供商(基于Oracle,带有会话表和各种奇怪的东西)对用户进行身份验证的方法。我们计划在不久的将来解决这个问题,但目前我们必须解决这个问题,所以我们的想法是在前线使用KeyClope——利用它提供的主要好处,比如SSO——在需要身份验证的应用程序中省略传统的身份验证提供程序。 我读了一些关于构建自定义OIDC身份提供程