keycloak CORS过滤器弹簧靴

krs*_*888 12 java rest spring cors keycloak

我正在使用keycloak来确保我的休息服务.我正在参考这里给出的教程.我创造了休息和前端.现在当我在后端添加keycloak时,当我的前端进行api调用时,我收到CORS错误.

Spring启动时的Application.java文件看起来像

@SpringBootApplication
public class Application 
{
    public static void main( String[] args )
    {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfiguration() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/*")
                        .allowedMethods(HttpMethod.GET.toString(), HttpMethod.POST.toString(),
                                HttpMethod.PUT.toString(), HttpMethod.DELETE.toString(), HttpMethod.OPTIONS.toString())
                        .allowedOrigins("*");
            }
        };
    }
} 
Run Code Online (Sandbox Code Playgroud)

application.properties文件中的keycloak属性如下所示

keycloak.realm = demo
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = tutorial-backend
keycloak.bearer-only = true
keycloak.credentials.secret = 123123-1231231-123123-1231
keycloak.cors = true
keycloak.securityConstraints[0].securityCollections[0].name = spring secured api
keycloak.securityConstraints[0].securityCollections[0].authRoles[0] = admin
keycloak.securityConstraints[0].securityCollections[0].authRoles[1] = user
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /api/*
Run Code Online (Sandbox Code Playgroud)

我正在调用的示例REST API

@RestController
public class SampleController {    
    @RequestMapping(value ="/api/getSample",method=RequestMethod.GET)
    public string home() {
        return new string("demo");
    }        
}
Run Code Online (Sandbox Code Playgroud)

前端keycloak.json属性包括

{
  "realm": "demo",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "tutorial-frontend",
  "public-client": true
}
Run Code Online (Sandbox Code Playgroud)

我得到的CORS错误

XMLHttpRequest cannot load http://localhost:8090/api/getSample. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 401.
Run Code Online (Sandbox Code Playgroud)

小智 7

我知道..问题很老了。但是如果您在使用 Spring Boot + Keycloak 进行本地开发时遇到问题,您可以使用 Config

keycloak.cors=true
Run Code Online (Sandbox Code Playgroud)

在你的 application.properties 中。

干杯:)


Gre*_*eek 0

当您的客户端发送 Authentication 标头时,您不能使用 allowedOrigins("*")。您必须配置特定的源 URL。

  • 那是行不通的。我将 allowedOrigins 更改为运行客户端的 URL。在我的项目中,它在 localhost:9000 上运行。即使更改后我仍然收到错误 (2认同)