keycloak CORS 过滤器弹簧靴
我正在使用 keycloak 来保护我的休息服务.我指的是 here 给出的教程.我创建了其余部分和前端.现在,当我在后端添加 keycloak 时,当我的前端调用 api 时出现 CORS 错误.
I am using keycloak to secure my rest service. I am refering to the tutorial given here. I created the rest and front end. Now when I add keycloak on the backend I get CORS error when my front end makes api call.
Spring Boot 中的 Application.java 文件看起来像
Application.java file in spring boot looks like
@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("*");
}
};
}
}
application.properties 文件中的 keycloak 属性如下所示
The keycloak properties in the application.properties file look like
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/*
我正在调用的示例 REST API
The sample REST API that I am calling
@RestController
public class SampleController {
@RequestMapping(value ="/api/getSample",method=RequestMethod.GET)
public string home() {
return new string("demo");
}
}
前端keycloak.json属性包括
the front end keycloak.json properties include
{
"realm": "demo",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "tutorial-frontend",
"public-client": true
}
我得到的 CORS 错误
The CORS error that I get
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.
推荐答案
我知道.. 问题很老了.但是,如果您在使用 Spring Boot + Keycloak 进行本地开发时遇到问题,您可以使用 Config
I know.. the Problem is quite Old. But if you've Problems with the local development with Spring Boot + Keycloak you can use the Config
keycloak.cors=true
在您的 application.properties 中.
in your application.properties.
干杯:)
相关文章