钥匙斗篷CORS过滤器弹簧靴 [英] keycloak CORS filter spring boot

查看:83
本文介绍了钥匙斗篷CORS过滤器弹簧靴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用密钥斗篷来保护我的休息服务.我指的是此处给出的教程.我创建了其余部分和前端.现在,当我在后端添加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错误

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.

推荐答案

尝试像我的示例一样创建CORS bean.我最近经历了同样的事情(让CORS正常工作),这是一场噩梦,因为SpringBoot CORS支持目前不像MVC CORS那样强大或直接.

Try creating your CORS bean like my example. I recently went through the same thing (getting CORS to work) and it was a nightmare because the SpringBoot CORS support is currently not as robust or straightforward as the MVC CORS.

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);

    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

这是我将其设置为接受应用程序范围内任何原始源的方式,但是,如果您更改了一些参数,则应该能够复制所需的内容. IE.如果只想添加您提到的方法,请链接一些addAllowedMethod().允许的来源相同,然后您的addMapping("/api/*")将变为source.registerCorsConfiguration("/api/*", config);.

This is how I set it up to accept any origin application-wide, but if you change a few of the parameters you should be able to replicate what you want. ie. if you wanted to add only the methods you mentioned, chain some addAllowedMethod(). Allowed origins would be the same, and then your addMapping("/api/*") would become source.registerCorsConfiguration("/api/*", config);.

Spring Data Rest和Cors

看看这个. Sebastian是Spring工程团队的成员,所以这和您获得正式答案的能力差不多.

Take a look at this. Sebastian is on the Spring engineering team so this is about as good as you're going to get for an official answer.

这篇关于钥匙斗篷CORS过滤器弹簧靴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆