Enabling CORS in Spring Secondary Servlet - spring

I am registering a secondary servlet using Spring boot's ServletRegistrationBean
#Configuration
public class CxfServletRegister {
#Bean
public ServletRegistrationBean getODataServletRegistrationBean() {
ServletRegistrationBean odataServletRegistrationBean = new ServletRegistrationBean(new CXFNonSpringJaxrsServlet(), "/odata.svc/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("javax.ws.rs.Application", "org.apache.olingo.odata2.core.rest.app.ODataApplication");
initParameters.put("org.apache.olingo.odata2.service.factory", "com.cce.utils.JPAServiceFactory");
odataServletRegistrationBean.setInitParameters(initParameters);
return odataServletRegistrationBean;
}
}
I am building an OData application using Apache Olingo. I want CORS to be enabled for my service.
How do I enable CORS for this servlet?
PS I have tried the WebConfigurer bean from the Spring: Getting Started guides
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("*");
}
};
}
This doesn't work, probably because this is configuring spring web's default dispatcher servlet and not the additional servlet configured using the ServletRegistrationBean

I found a likely way to do it here:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
#Configuration
public class MyConfiguration {
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}

Related

Keycloak Multitenancy static Content Return 404

I'm working on modernizing monolithic application to be microservice based application supporting multi tenancy using Spring boot, Keycloak 17, the configuration is Keycloak configuration file depending on the path referring to this example
For me it it working, and can load the deployments from json, login, below is the url for the application and I'm parsing branch1 after "tenant" without issues
http://localhost:8100/tenant/branch1/
The main issue is rendering css and JS files which is containing tenant name knwoing that I'm using sing WAR
with multiple realms
http://localhost:8100/tenant/branch1/resources/bootstrap/js/bootstrap.min.js --> return 404 which is not exist
Actual code for including static contents
in The jsp files I'm reading css/js files as before <link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css">
keycloal json file example
{"realm": "branch1",
"auth-server-url": "http://localhost:8181/",
"ssl-required": "external",
"resource": "app",
"public-client": true,
"confidential-port": 0,
"principal-attribute": "preferred_username"}
Please advise
rendering static content
is there any guidance after authentication to return one URL without tenant/branch1 specially I'm using CurrentTenantIdentifierResolver inside my application
#ConditionalOnProperty(prefix = "keycloak.config", name = "resolver", havingValue = "path")
public class PathBasedConfigResolver implements KeycloakConfigResolver {
private final ConcurrentHashMap<String, KeycloakDeployment> cache = new ConcurrentHashMap<>();
#SuppressWarnings("unused")
private static AdapterConfig adapterConfig;
#Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
System.out.println("inside resolve :: ");
String realm = SubdomainUtils.obtainTenantFromSubdomain(request.getURI());
if (realm.contains("?")) {
realm = realm.split("\\?")[0];
}
if (!cache.containsKey(realm)) {
InputStream is = this.getClass().getResourceAsStream("/" + realm + "-keycloak.json");
cache.put(realm, KeycloakDeploymentBuilder.build(is));
}
return cache.get(realm);
}
static void setAdapterConfig(AdapterConfig adapterConfig) {
PathBasedConfigResolver.adapterConfig = adapterConfig;
}
}
public class SpringKeycloakSecurityConfiguration {
#DependsOn("keycloakConfigResolver")
#KeycloakConfiguration
#ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public static class KeycloakConfigurationAdapter extends KeycloakWebSecurityConfigurerAdapter {
/**
* Registers the KeycloakAuthenticationProvider with the authentication manager.
*/
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
SimpleAuthorityMapper soa = new SimpleAuthorityMapper();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(soa);
auth.authenticationProvider(keycloakAuthenticationProvider);
}
/**
* Defines the session authentication strategy.
*/
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
// required for bearer-only applications.
// return new NullAuthenticatedSessionStrategy();
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
#Override
protected AuthenticationEntryPoint authenticationEntryPoint() throws Exception {
return new MultitenantKeycloakAuthenticationEntryPoint(adapterDeploymentContext());
}
#Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(
authenticationManager(), new AntPathRequestMatcher("/tenant/*/sso/login"));
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
return filter;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
KeycloakAuthenticationProcessingFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
KeycloakPreAuthActionsFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean(
KeycloakAuthenticatedActionsFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakSecurityContextRequestFilterBean(
KeycloakSecurityContextRequestFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#Bean
#Override
#ConditionalOnMissingBean(HttpSessionManager.class)
protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
/**
* Configuration spécifique à keycloak (ajouts de filtres, etc)
*
* #param http
* #throws Exception
*/
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
// use previously declared bean
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
// keycloak filters for securisation
.and().addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and().logout().addLogoutHandler(keycloakLogoutHandler()).logoutUrl("/tenant/*/logout")
.logoutSuccessHandler(
// logout handler for API
(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) -> response.setStatus(HttpServletResponse.SC_OK))
.and().authorizeRequests().antMatchers("mobileservlet/**").permitAll().antMatchers("**/favicon.ico")
.permitAll().antMatchers("/error").permitAll().antMatchers("/login.go").permitAll()
.antMatchers("/resources/*").permitAll().anyRequest().authenticated();
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList(HttpMethod.OPTIONS.name(), "GET", "POST"));
configuration.setAllowedHeaders(
Arrays.asList("Access-Control-Allow-Headers", "Access-Control-Allow-Origin", "Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
}
public class MultitenantKeycloakAuthenticationEntryPoint extends KeycloakAuthenticationEntryPoint {
public MultitenantKeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext) {
super(adapterDeploymentContext);
}
public MultitenantKeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext, RequestMatcher apiRequestMatcher) {
super(adapterDeploymentContext, apiRequestMatcher);
}
#Override
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("inside commenceLoginRedirect :: ");
String path = request.getRequestURI();
int multitenantIndex = path.indexOf("tenant/");
if (multitenantIndex == -1) {
throw new IllegalStateException("Not able to resolve the realm from the request path!");
}
String realm = path.substring(path.indexOf("tenant/")).split("/")[1];
if (realm.contains("?")) {
realm = realm.split("\\?")[0];
}
String contextAwareLoginUri = request.getContextPath() + "/tenant/" + realm + DEFAULT_LOGIN_URI;
response.sendRedirect(contextAwareLoginUri);
}
}
Bad news, the Keycloak adapters for spring you are using are very deprecated. Don't use it.
Better news, I host spring-boot starters for resource-servers which support multi-tenancy: accept identities issued by more than just one issuer (as many realms as you need in your case) and retrieve "roles" from realms and clients with the mapping you want (control case and prefix). It also enables you to configure "public" routes and CORS configuration from preperties file (plus a few more things).
Configuration for realm1 and other-realm both used by two clients (some client and other-client) is as simple as:
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<!-- replace "webflux" with "webmvc" if your app is a servlet -->
<!-- replace "jwt" with "introspecting" to use token introspection instead of JWT decoding -->
<artifactId>spring-addons-webflux-jwt-resource-server</artifactId>
<!-- this version is to be used with spring-boot 3.0.0-RC2, use 5.x for spring-boot 2.6.x or before -->
<version>6.0.5</version>
</dependency>
#EnableMethodSecurity
public static class WebSecurityConfig { }
com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm1
com.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles
com.c4-soft.springaddons.security.issuers[1].location=https://localhost:8443/realms/other-realm
com.c4-soft.springaddons.security.issuers[1].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles
com.c4-soft.springaddons.security.cors[0].path=/some-api

How Can I Disable ssl certificate Spring RestTemplate?

In my Spring boot project I am trying to intercept the following POST call "https: // localhost: 8080" but I get the following error:
java.lang.IllegalArgumentException: Invalid character found in method name
I already know that to solve the problem it would be enough to change from https to http. But I don't want this.
I want my code to be able to automatically handle this situation.
In any case if I try to reach
This is the configuration of my RestTemplate in the App class:
How could I go about solving the problem ??
This is the configuration of my RestTemplate in the App class:
#EnableFeignClients
#ServletComponentScan
#Import(EmbeddedTomcatConfiguration.class)
// uncomment to enable auditor
//#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
return restTemplate;
}
#Autowired(required = true)
public void configureJackson(ObjectMapper jackson2ObjectMapper) {
// jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jackson2ObjectMapper.registerModule(new JavaTimeModule());
jackson2ObjectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
#Bean
public FilterRegistrationBean<CorsFilter> filterRegistrationBean() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = buildCorsConfiguration();
source.registerCorsConfiguration("/**", config);
final FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
private CorsConfiguration buildCorsConfiguration() {
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addExposedHeader(HttpHeaders.LOCATION);
return config;
}
}
How could I go about solving the problem ??

How to fix Cors error Access-Control-Allow-Origin missing

I have a spring boot rest application and I am not using Spring security. My rest service looks like this
#RestController
#CrossOrigin
public class AuthenticationService {
...
#GetMapping(path = "/getUser")
public JSONObject getUser() {
...
}
}
I call the API from a REST application using axios get. Everything works fine locally.
But when the application is deployed on cloud as a docker image, I get the 403 error
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Even when I add a CorsConfiguration file I get the same error.
#Configuration
public class CorsConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedHeaders("Accept", "Origin", "X-Requested-With,Content-Type", "Authorization", "X-XSRF-Header")
.allowCredentials(true);
}
};
}
}
I have spent a lot of time to find a solution for this but somehow it isn't working.
Declaring a bean works fine for me:
#Configuration
public class WebConfigurer implements ServletContextInitializer, WebMvcConfigurer {
private final Environment env;
private final MyProperties properties;
public WebConfigurer(Environment env, MyProperties properties) {
this.env = env;
this.properties = properties;
}
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = properties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
}
return new CorsFilter(source);
}
}
Yaml properties:
# CORS is only enabled by default with the "dev" profile
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800
fixed by adding spring security

NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters

I want to configure Spring application with Hibernate. I tried this:
Main start method:
#Configuration
#EnableWebMvc
public class WebConfig implements WebApplicationInitializer, WebMvcConfigurer {
private BasicAuthenticationInterceptor basicAuthenticationInterceptor;
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
converters.add(new MappingJackson2XmlHttpMessageConverter(
((XmlMapper) createObjectMapper(Jackson2ObjectMapperBuilder.xml()))
.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)));
converters.add(new MappingJackson2HttpMessageConverter(
createObjectMapper(Jackson2ObjectMapperBuilder.json())));
}
private ObjectMapper createObjectMapper(Jackson2ObjectMapperBuilder builder) {
builder.indentOutput(true);
builder.modules(new JaxbAnnotationModule());
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.defaultUseWrapper(false);
return builder.build();
}
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ContextDatasource.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
#Autowired
public void setBasicAuthenticationInterceptor(BasicAuthenticationInterceptor basicAuthenticationInterceptor) {
this.basicAuthenticationInterceptor = basicAuthenticationInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(basicAuthenticationInterceptor);
}
}
Hibernate configuration called from rootContext.register(ContextDatasource.class);:
#SpringBootApplication
#Configuration
#EnableTransactionManagement
public class ContextDatasource {
#Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
return new FastJsonHttpMessageConverter();
}
#Bean
#Autowired
public HttpMessageConverters convertersToBeUsed(FastJsonHttpMessageConverter converter) {
return new HttpMessageConverters(converter);
}
#Bean
public LocalSessionFactoryBean getSessionFactory() throws NamingException {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
sessionFactory.setPackagesToScan(new String[] { "org.datalis.plugin.database.models" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource getDataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup("java:/global/production_gateway");
}
#Bean
public PlatformTransactionManager getHibernateTransactionManager() throws NamingException {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor getExceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.format_sql", "true");
return hibernateProperties;
}
}
But when I deploy the WAR file I get error:
Caused by: java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters$$EnhancerBySpringCGLIB$$1d90bff9.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3302)
Full error stack:
https://pastebin.com/x30W2aws
Can you give advice where I'm wrong and how to fix the problem?
Do I need to implement the module startup with another configuration?
EDIT:
With Java 8 the code is working without above issue. With latest Java 10 I get the above exception. Do you know what configuration I need to do?
According to the Spring Boot release notes, Java 10 is supported by Spring Boot version 2.0.1 and up. Without a list of your dependencies it's impossible to know if this is the issue, but it does seem like a good place to start.
Are you running Boot v2.0.1 or higher?

Enabling Cross Origin Resource Sharing for Spring Data Rest

I'm developing Spring (non-Boot) application with Spring 4.2.1 version. I've enabled CORS for Spring MVC in web configuration file.
#Configuration
#EnableWebMvc
#ComponentScan({"com.hello.web", "com.hello.rest"})
#Import(RestMvcConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
And it was working correct. But now i started to use String Data Rest 2.4 and integrated it with Spring MVC. How to enable Cross Origin Resources Sharing for Spring Data Rest controllers? I've tried to fix it with filter bean Spring Data Rest and Cors
#Configuration
public class RestMvcConfig extends RepositoryRestMvcConfiguration {
#Override
public RepositoryRestConfiguration config() {
RepositoryRestConfiguration config = super.config();
config.setBasePath("/api");
config.setDefaultMediaType(new MediaType("application", "json", Charset.forName("utf-8")));
return config;
}
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // you USUALLY want this
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
But CORS is still not allowed.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
How to enable CORS for Spring Data Rest?

Resources