【问题标题】:Spring security (HttpSecurity) with keycloak setup带有 keycloak 设置的 Spring Security (HttpSecurity)
【发布时间】:2021-07-04 00:25:49
【问题描述】:

我有以下设置:

  1. 一个基于角度的前端,它与一个通信
  2. 基于 java 的后端,反过来进行通信
  3. 在组织中提供第 3 方服务。

前端/后端访问由查询 keycloak 服务器的 oauth2 保护。这个 keycloak 服务器对我的应用程序和我的后端正在访问的 3rd 方服务的用户进行身份验证。 获取第三方服务访问令牌的代码如下(其实这就是问题所在的代码:调用template.getAccessToken()时,另见下文):

  private void setAccessToken(HttpRequest request) {
    HttpHeaders headers = new HttpHeaders();
    OAuth2RestTemplate template = new OAuth2RestTemplate(resourceOwnerDetails());
    OAuth2AccessToken accessToken = template.getAccessToken();
    headers.setAuthorization("Bearer " + accessToken);
    request.setHeaders(headers);
  }

安全配置如下:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
      http.requiresChannel()
          .anyRequest()
          .requiresSecure()
          .and()
          .cors()
          .and()
          .csrf()
          .disable()
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
          .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
          .and()
          .authorizeRequests()
          .antMatchers("/accessdenied", "/accessdenied/**", "/style/*")
          .permitAll()
          .antMatchers("/")
          .hasAnyRole(allowedRoles)
          .anyRequest()
          .hasAnyRole(allowedRoles)
          .and()
          .exceptionHandling()
          .accessDeniedPage("/accessdenied");

当需要对前端/GUI 访问和后端查询的 3rd 方服务进行身份验证时,这可以正常工作。

我的问题如下: 在某些条件下(测试人员),我希望用户不必为前端/GUI 访问进行身份验证。但是,为了访问第 3 方服务,始终需要进行身份验证。

要在没有身份验证的情况下访问前端,我可以做一个简单的配置,例如:

 http.authorizeRequests().antMatchers("/**").permitAll().and().csrf().disable();

有了这个,我可以在没有经过身份验证的情况下访问 GUI(这是我想要的),但是当通过 template.getAccessToken()(见上文)获取 oauth2 访问令牌时,会引发异常

org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)

所以,我认为我正在寻找的是正确的安全配置。 如何配置 Spring Security 使其不验证 GUI/前端访问但仍获取第 3 方服务的访问令牌?非常感谢任何指向正确方向的指针。

【问题讨论】:

    标签: java spring security keycloak


    【解决方案1】:

    在 pom.xml 中

    <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    

    在你的配置类中

        import org.springframework.security.oauth2.provider.token.TokenStore;
        import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
    
        @Configuration
        @EnableResourceServer
    
        public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
            @Bean
            public TokenStore tokenStore() {
                return new JwkTokenStore("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs");
            }
        }
    
        import org.springframework.security.oauth2.provider.token.TokenStore;
        import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
    
        @KeycloakConfiguration
        @Configuration
        @EnableWebSecurity
        @ComponentScan(
            basePackageClasses = KeycloakSecurityComponents.class
        )
        @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
        public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
            @Bean
            public TokenStore tokenStore() {
                return new JwkTokenStore("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs");
            }
        }
    

    【讨论】:

    • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
    猜你喜欢
    • 2020-03-04
    • 2017-10-18
    • 2016-08-08
    • 2021-06-29
    • 1970-01-01
    • 2016-03-14
    • 2023-04-02
    • 2021-12-15
    • 2017-09-21
    相关资源
    最近更新 更多