Search in sources :

Example 6 with CorsConfiguration

use of org.springframework.web.cors.CorsConfiguration in project spring-framework by spring-projects.

the class CorsUrlHandlerMappingTests method preFlightRequestWithGlobalCorsConfig.

@Test
public void preFlightRequestWithGlobalCorsConfig() throws Exception {
    CorsConfiguration mappedConfig = new CorsConfiguration();
    mappedConfig.addAllowedOrigin("*");
    this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/welcome.html", mappedConfig));
    String origin = "http://domain2.com";
    ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin);
    Object actual = this.handlerMapping.getHandler(exchange).block();
    assertNotNull(actual);
    assertNotSame(this.welcomeController, actual);
    assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) Test(org.junit.Test)

Example 7 with CorsConfiguration

use of org.springframework.web.cors.CorsConfiguration in project spring-framework by spring-projects.

the class CorsBeanDefinitionParser method parse.

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    Map<String, CorsConfiguration> corsConfigurations = new LinkedHashMap<>();
    List<Element> mappings = DomUtils.getChildElementsByTagName(element, "mapping");
    if (mappings.isEmpty()) {
        CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
        corsConfigurations.put("/**", config);
    } else {
        for (Element mapping : mappings) {
            CorsConfiguration config = new CorsConfiguration();
            if (mapping.hasAttribute("allowed-origins")) {
                String[] allowedOrigins = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-origins"), ",");
                config.setAllowedOrigins(Arrays.asList(allowedOrigins));
            }
            if (mapping.hasAttribute("allowed-methods")) {
                String[] allowedMethods = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-methods"), ",");
                config.setAllowedMethods(Arrays.asList(allowedMethods));
            }
            if (mapping.hasAttribute("allowed-headers")) {
                String[] allowedHeaders = StringUtils.tokenizeToStringArray(mapping.getAttribute("allowed-headers"), ",");
                config.setAllowedHeaders(Arrays.asList(allowedHeaders));
            }
            if (mapping.hasAttribute("exposed-headers")) {
                String[] exposedHeaders = StringUtils.tokenizeToStringArray(mapping.getAttribute("exposed-headers"), ",");
                config.setExposedHeaders(Arrays.asList(exposedHeaders));
            }
            if (mapping.hasAttribute("allow-credentials")) {
                config.setAllowCredentials(Boolean.parseBoolean(mapping.getAttribute("allow-credentials")));
            }
            if (mapping.hasAttribute("max-age")) {
                config.setMaxAge(Long.parseLong(mapping.getAttribute("max-age")));
            }
            corsConfigurations.put(mapping.getAttribute("path"), config.applyPermitDefaultValues());
        }
    }
    MvcNamespaceUtils.registerCorsConfigurations(corsConfigurations, parserContext, parserContext.extractSource(element));
    return null;
}
Also used : CorsConfiguration(org.springframework.web.cors.CorsConfiguration) Element(org.w3c.dom.Element) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with CorsConfiguration

use of org.springframework.web.cors.CorsConfiguration in project spring-framework by spring-projects.

the class AbstractHandlerMapping method getHandler.

/**
	 * Look up a handler for the given request, falling back to the default
	 * handler if no specific one is found.
	 * @param request current HTTP request
	 * @return the corresponding handler instance, or the default handler
	 * @see #getHandlerInternal
	 */
@Override
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    Object handler = getHandlerInternal(request);
    if (handler == null) {
        handler = getDefaultHandler();
    }
    if (handler == null) {
        return null;
    }
    // Bean name or resolved handler?
    if (handler instanceof String) {
        String handlerName = (String) handler;
        handler = getApplicationContext().getBean(handlerName);
    }
    HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
    if (CorsUtils.isCorsRequest(request)) {
        CorsConfiguration globalConfig = this.globalCorsConfigSource.getCorsConfiguration(request);
        CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
        CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
        executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
    }
    return executionChain;
}
Also used : CorsConfiguration(org.springframework.web.cors.CorsConfiguration) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain)

Example 9 with CorsConfiguration

use of org.springframework.web.cors.CorsConfiguration in project spring-framework by spring-projects.

the class MvcNamespaceTests method testCorsMinimal.

@Test
public void testCorsMinimal() throws Exception {
    loadBeanDefinitions("mvc-config-cors-minimal.xml", 14);
    String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
    assertEquals(2, beanNames.length);
    for (String beanName : beanNames) {
        AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) appContext.getBean(beanName);
        assertNotNull(handlerMapping);
        Map<String, CorsConfiguration> configs = handlerMapping.getCorsConfigurations();
        assertNotNull(configs);
        assertEquals(1, configs.size());
        CorsConfiguration config = configs.get("/**");
        assertNotNull(config);
        assertArrayEquals(new String[] { "*" }, config.getAllowedOrigins().toArray());
        assertArrayEquals(new String[] { "GET", "HEAD", "POST" }, config.getAllowedMethods().toArray());
        assertArrayEquals(new String[] { "*" }, config.getAllowedHeaders().toArray());
        assertNull(config.getExposedHeaders());
        assertTrue(config.getAllowCredentials());
        assertEquals(Long.valueOf(1800), config.getMaxAge());
    }
}
Also used : CorsConfiguration(org.springframework.web.cors.CorsConfiguration) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.Test)

Example 10 with CorsConfiguration

use of org.springframework.web.cors.CorsConfiguration in project spring-framework by spring-projects.

the class MvcNamespaceTests method testCors.

@Test
public void testCors() throws Exception {
    loadBeanDefinitions("mvc-config-cors.xml", 14);
    String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
    assertEquals(2, beanNames.length);
    for (String beanName : beanNames) {
        AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) appContext.getBean(beanName);
        assertNotNull(handlerMapping);
        Map<String, CorsConfiguration> configs = handlerMapping.getCorsConfigurations();
        assertNotNull(configs);
        assertEquals(2, configs.size());
        CorsConfiguration config = configs.get("/api/**");
        assertNotNull(config);
        assertArrayEquals(new String[] { "http://domain1.com", "http://domain2.com" }, config.getAllowedOrigins().toArray());
        assertArrayEquals(new String[] { "GET", "PUT" }, config.getAllowedMethods().toArray());
        assertArrayEquals(new String[] { "header1", "header2", "header3" }, config.getAllowedHeaders().toArray());
        assertArrayEquals(new String[] { "header1", "header2" }, config.getExposedHeaders().toArray());
        assertFalse(config.getAllowCredentials());
        assertEquals(Long.valueOf(123), config.getMaxAge());
        config = configs.get("/resources/**");
        assertArrayEquals(new String[] { "http://domain1.com" }, config.getAllowedOrigins().toArray());
        assertArrayEquals(new String[] { "GET", "HEAD", "POST" }, config.getAllowedMethods().toArray());
        assertArrayEquals(new String[] { "*" }, config.getAllowedHeaders().toArray());
        assertNull(config.getExposedHeaders());
        assertTrue(config.getAllowCredentials());
        assertEquals(Long.valueOf(1800), config.getMaxAge());
    }
}
Also used : CorsConfiguration(org.springframework.web.cors.CorsConfiguration) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.Test)

Aggregations

CorsConfiguration (org.springframework.web.cors.CorsConfiguration)44 Test (org.junit.Test)27 HandlerExecutionChain (org.springframework.web.servlet.HandlerExecutionChain)15 HandlerMethod (org.springframework.web.method.HandlerMethod)7 Bean (org.springframework.context.annotation.Bean)4 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)3 ServerWebExchange (org.springframework.web.server.ServerWebExchange)3 HandlerInterceptor (org.springframework.web.servlet.HandlerInterceptor)3 List (java.util.List)2 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)2 ConditionalOnBean (org.springframework.boot.autoconfigure.condition.ConditionalOnBean)2 CrossOrigin (org.springframework.web.bind.annotation.CrossOrigin)2 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)2 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)2 UrlBasedCorsConfigurationSource (org.springframework.web.cors.UrlBasedCorsConfigurationSource)2 CorsFilter (org.springframework.web.filter.CorsFilter)2 AbstractHandlerMapping (org.springframework.web.servlet.handler.AbstractHandlerMapping)2 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 HttpWebRequestProperties (org.apereo.cas.configuration.model.core.web.security.HttpWebRequestProperties)1