首页 > 解决方案 > Keycloak 在 Spring Boot 项目中无法处理根 URL

问题描述

我在 spring boot 项目中使用 keyclaok 效果很好。但在基本 URL ("/") 中不起作用

localhost:3000/hello working(显示 keycloak 登录页面)

localhost:3000/app1 工作(不显示 keycloak 登录页面,我确实允许)

localhost:3000/ 不工作(不显示 keycloak 登录页面和强制加载 index.html)

密钥斗篷配置

@Configuration
@EnableWebSecurity
public class KeycloakConfig extends KeycloakWebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    KeycloakAuthenticationProvider 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("/app*").permitAll()
        .anyRequest().authenticated();
  }

  @Bean
  public KeycloakConfigResolver keycloakConfigResolver() {
    return new KeycloakConfigResolver() {
      private KeycloakDeployment keycloakDeployment;

      @Override
      public KeycloakDeployment resolve(HttpFacade.Request facade) {
        if (keycloakDeployment != null) {
          return keycloakDeployment;
        }
        InputStream configInputStream = getClass().getResourceAsStream("/keycloak.json");
        return KeycloakDeploymentBuilder.build(configInputStream);
      }
    };
  }
}

样品控制器

@Controller
public class SampleController {

  @RequestMapping("/")
  public String index() {
    return "index";
  }

  @RequestMapping("/hello")
  @ResponseBody
  public String hello() {
    return "Hello KeyCloak!";
  }

  @RequestMapping("/app1")
  @ResponseBody
  public String tracingTest() {
    return "This is permitAll!";
  }
}

密钥斗篷.json

{
  "realm": "myrelam",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "myapp",
  "credentials": {
    "secret": "XXX..."
  },
  "confidential-port": 0
}

我还在 keycloak 控制台上向我的客户端添加了重定向 URL (localhost:3000/*)

标签: keycloak

解决方案


尝试配置您的客户端网址,如下图所示

在此处输入图像描述

并将@ResponseBody 添加到“index”方法,否则您必须添加 index.html 页面


推荐阅读