Java Code Examples for org.springframework.web.cors.CorsUtils

The following examples show how to use org.springframework.web.cors.CorsUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Check if any of the HTTP request methods match the given request and
 * return an instance that contains the matching HTTP request method only.
 * @param request the current request
 * @return the same instance if the condition is empty (unless the request
 * method is HTTP OPTIONS), a new condition with the matched request method,
 * or {@code null} if there is no match or the condition is empty and the
 * request method is OPTIONS.
 */
@Override
@Nullable
public RequestMethodsRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return matchPreFlight(request);
	}

	if (getMethods().isEmpty()) {
		if (RequestMethod.OPTIONS.name().equals(request.getMethod()) &&
				!DispatcherType.ERROR.equals(request.getDispatcherType())) {

			return null; // We handle OPTIONS transparently, so don't match if no explicit declarations
		}
		return this;
	}

	return matchRequestMethod(request.getMethod());
}
 
Example 2
Source Project: spring-analysis-note   Source File: FrameworkServlet.java    License: MIT License 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper in order to always add PATCH to the allowed methods
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 3
Source Project: cymbal   Source File: SecurityConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable();
    http.csrf().disable();

    http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .antMatchers("/api/**").permitAll()
            .anyRequest().authenticated();

    http.logout().permitAll();

    http.exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint).and()
            .addFilter(this.authenticationProcessingFilter)
            .addFilterBefore(this.logoutFilter, authenticationProcessingFilter.getClass())
            .addFilterBefore(this.singleSignOutFilter, authenticationProcessingFilter.getClass());
}
 
Example 4
Source Project: java-technology-stack   Source File: ConsumesRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match
 */
@Override
@Nullable
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}

	MediaType contentType;
	try {
		contentType = (StringUtils.hasLength(request.getContentType()) ?
				MediaType.parseMediaType(request.getContentType()) :
				MediaType.APPLICATION_OCTET_STREAM);
	}
	catch (InvalidMediaTypeException ex) {
		return null;
	}

	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<>(this.expressions);
	result.removeIf(expression -> !expression.match(contentType));
	return (!result.isEmpty() ? new ConsumesRequestCondition(result) : null);
}
 
Example 5
/**
 * Check if any of the HTTP request methods match the given request and
 * return an instance that contains the matching HTTP request method only.
 * @param request the current request
 * @return the same instance if the condition is empty (unless the request
 * method is HTTP OPTIONS), a new condition with the matched request method,
 * or {@code null} if there is no match or the condition is empty and the
 * request method is OPTIONS.
 */
@Override
@Nullable
public RequestMethodsRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return matchPreFlight(request);
	}

	if (getMethods().isEmpty()) {
		if (RequestMethod.OPTIONS.name().equals(request.getMethod()) &&
				!DispatcherType.ERROR.equals(request.getDispatcherType())) {

			return null; // No implicit match for OPTIONS (we handle it)
		}
		return this;
	}

	return matchRequestMethod(request.getMethod());
}
 
Example 6
Source Project: java-technology-stack   Source File: FrameworkServlet.java    License: MIT License 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper in order to always add PATCH to the allowed methods
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 7
Source Project: java-technology-stack   Source File: CorsFilter.java    License: MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	if (CorsUtils.isCorsRequest(request)) {
		CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
		if (corsConfiguration != null) {
			boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
			if (!isValid || CorsUtils.isPreFlightRequest(request)) {
				return;
			}
		}
	}

	filterChain.doFilter(request, response);
}
 
Example 8
Source Project: halo   Source File: CorsFilter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // Set customized header
    String originHeaderValue = httpServletRequest.getHeader(HttpHeaders.ORIGIN);
    if (StringUtils.isNotBlank(originHeaderValue)) {
        httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderValue);
    }
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ALLOW_HEADERS);
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS");
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");

    if (!CorsUtils.isPreFlightRequest(httpServletRequest)) {
        chain.doFilter(httpServletRequest, httpServletResponse);
    }
}
 
Example 9
Source Project: poseidon   Source File: SecurityTokenConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(HttpSecurity http) throws Exception {
	http.csrf().disable().cors().and()
			// make sure we use stateless session; session won't be used to store
			// user's state.
			.sessionManagement()
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
			// handle an authorized attempts
			.exceptionHandling()
			.authenticationEntryPoint((req, rsp, e) -> rsp
					.sendError(HttpServletResponse.SC_UNAUTHORIZED))
			.and()
			// Add a filter to validate the tokens with every request
			.addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig),
					UsernamePasswordAuthenticationFilter.class)
			// authorization requests config
			.authorizeRequests().requestMatchers(CorsUtils::isCorsRequest).permitAll()
			.antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
			.antMatchers(HttpMethod.GET, router.getWeb_shop_cart_service(),
					router.getWeb_view_service(), router.getMember_service())
			.permitAll()
			// required here)
			// .antMatchers("/view" + "/admin/**").hasRole("")
			// Any other request must be authenticated
			.anyRequest().authenticated();
}
 
Example 10
Source Project: fish-admin   Source File: WebSecurityConfig.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()
            .authorizeRequests()
            // All urls must be authenticated (filter for token always fires (/**)
            .antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .anyRequest().authenticated()
            .and()
            // Call our errorHandler if authentication/authorisation fails
            .exceptionHandling()
            .authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"))
            .and()
            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
            .and().addFilterBefore(new JwtAuthenticationTokenFilter("/login", authenticationManager()),
                    UsernamePasswordAuthenticationFilter.class)
            // 添加一个过滤器验证其他请求的Token是否合法
            .addFilterBefore(new JWTAuthenticationFilter(),
                    UsernamePasswordAuthenticationFilter.class);
    // disable page caching
    httpSecurity.headers().cacheControl();
}
 
Example 11
/**
 * Check if any of the HTTP request methods match the given request and
 * return an instance that contains the matching HTTP request method only.
 * @param request the current request
 * @return the same instance if the condition is empty (unless the request
 * method is HTTP OPTIONS), a new condition with the matched request method,
 * or {@code null} if there is no match or the condition is empty and the
 * request method is OPTIONS.
 */
@Override
public RequestMethodsRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return matchPreFlight(request);
	}

	if (getMethods().isEmpty()) {
		if (RequestMethod.OPTIONS.name().equals(request.getMethod()) &&
				!DispatcherType.ERROR.equals(request.getDispatcherType())) {

			return null; // No implicit match for OPTIONS (we handle it)
		}
		return this;
	}

	return matchRequestMethod(request.getMethod());
}
 
Example 12
Source Project: lams   Source File: AbstractHandlerMapping.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source Project: lams   Source File: FrameworkServlet.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper for Servlet 2.5 compatibility where
	// the getHeader() method does not exist
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + HttpMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 14
Source Project: lams   Source File: CorsFilter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	if (CorsUtils.isCorsRequest(request)) {
		CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
		if (corsConfiguration != null) {
			boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
			if (!isValid || CorsUtils.isPreFlightRequest(request)) {
				return;
			}
		}
	}

	filterChain.doFilter(request, response);
}
 
Example 15
/**
 * 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.corsConfigSource.getCorsConfiguration(request);
		CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
		CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
		executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
	}
	return executionChain;
}
 
Example 16
Source Project: spring4-understanding   Source File: FrameworkServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delegate OPTIONS requests to {@link #processRequest}, if desired.
 * <p>Applies HttpServlet's standard OPTIONS processing otherwise,
 * and also if there is still no 'Allow' header set after dispatching.
 * @see #doService
 */
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
		processRequest(request, response);
		if (response.containsHeader("Allow")) {
			// Proper OPTIONS response coming from a handler - we're done.
			return;
		}
	}

	// Use response wrapper for Servlet 2.5 compatibility where
	// the getHeader() method does not exist
	super.doOptions(request, new HttpServletResponseWrapper(response) {
		@Override
		public void setHeader(String name, String value) {
			if ("Allow".equals(name)) {
				value = (StringUtils.hasLength(value) ? value + ", " : "") + RequestMethod.PATCH.name();
			}
			super.setHeader(name, value);
		}
	});
}
 
Example 17
Source Project: pazuzu-registry   Source File: OAuthConfiguration.java    License: MIT License 6 votes vote down vote up
@Override
public void configure(final HttpSecurity http) throws Exception {

    // @formatter:off
    http
        .httpBasic()
            .disable()
        .anonymous()
        .and()
            .requestMatchers()
                .antMatchers("/api/**")
        .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER)
        .and()
            .authorizeRequests()
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .antMatchers("/api/health").permitAll()
            .antMatchers(HttpMethod.GET, "/api/**").permitAll()
            .antMatchers("/api/**").permitAll()
            //FIXME: disabled oauth
            .anyRequest().permitAll();
    // @formatter:on
}
 
Example 18
Source Project: spring-analysis-note   Source File: ConsumesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match
 */
@Override
@Nullable
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	if (!hasBody(request) && !this.bodyRequired) {
		return EMPTY_CONDITION;
	}

	// Common media types are cached at the level of MimeTypeUtils

	MediaType contentType;
	try {
		contentType = StringUtils.hasLength(request.getContentType()) ?
				MediaType.parseMediaType(request.getContentType()) :
				MediaType.APPLICATION_OCTET_STREAM;
	}
	catch (InvalidMediaTypeException ex) {
		return null;
	}

	List<ConsumeMediaTypeExpression> result = getMatchingExpressions(contentType);
	return !CollectionUtils.isEmpty(result) ? new ConsumesRequestCondition(result) : null;
}
 
Example 19
Source Project: spring-analysis-note   Source File: HeadersRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Returns "this" instance if the request matches all expressions;
 * or {@code null} otherwise.
 */
@Override
@Nullable
public HeadersRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	for (HeaderExpression expression : this.expressions) {
		if (!expression.match(request)) {
			return null;
		}
	}
	return this;
}
 
Example 20
Source Project: spring-analysis-note   Source File: ProducesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param request the current request
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	List<MediaType> acceptedMediaTypes;
	try {
		acceptedMediaTypes = getAcceptedMediaTypes(request);
	}
	catch (HttpMediaTypeException ex) {
		return null;
	}
	List<ProduceMediaTypeExpression> result = getMatchingExpressions(acceptedMediaTypes);
	if (!CollectionUtils.isEmpty(result)) {
		return new ProducesRequestCondition(result, this);
	}
	else if (MediaType.ALL.isPresentIn(acceptedMediaTypes)) {
		return EMPTY_CONDITION;
	}
	else {
		return null;
	}
}
 
Example 21
Source Project: spring-analysis-note   Source File: CorsFilter.java    License: MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
	boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
	if (!isValid || CorsUtils.isPreFlightRequest(request)) {
		return;
	}
	filterChain.doFilter(request, response);
}
 
Example 22
Source Project: zfile   Source File: CorsFilter.java    License: MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpServletRequest.getHeader(HttpHeaders.ORIGIN));
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept");
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS");
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");

    if (!CorsUtils.isPreFlightRequest(httpServletRequest)) {
        chain.doFilter(httpServletRequest, httpServletResponse);
    }
}
 
Example 23
Source Project: java-technology-stack   Source File: HeadersRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Returns "this" instance if the request matches all expressions;
 * or {@code null} otherwise.
 */
@Override
@Nullable
public HeadersRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	for (HeaderExpression expression : this.expressions) {
		if (!expression.match(request)) {
			return null;
		}
	}
	return this;
}
 
Example 24
Source Project: java-technology-stack   Source File: ProducesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param request the current request
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}

	List<MediaType> acceptedMediaTypes;
	try {
		acceptedMediaTypes = getAcceptedMediaTypes(request);
	}
	catch (HttpMediaTypeException ex) {
		return null;
	}

	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(this.expressions);
	result.removeIf(expression -> !expression.match(acceptedMediaTypes));
	if (!result.isEmpty()) {
		return new ProducesRequestCondition(result, this.contentNegotiationManager);
	}
	else if (MediaType.ALL.isPresentIn(acceptedMediaTypes)) {
		return EMPTY_CONDITION;
	}
	else {
		return null;
	}
}
 
Example 25
Source Project: java-technology-stack   Source File: AbstractHandlerMapping.java    License: MIT License 5 votes vote down vote up
/**
 * 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
@Nullable
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 = obtainApplicationContext().getBean(handlerName);
	}

	HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);

	if (logger.isTraceEnabled()) {
		logger.trace("Mapped to " + handler);
	}
	else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
		logger.debug("Mapped to " + executionChain.getHandler());
	}

	if (CorsUtils.isCorsRequest(request)) {
		CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
		CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
		CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
		executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
	}

	return executionChain;
}
 
Example 26
Source Project: java-technology-stack   Source File: AbstractSockJsService.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
	if (!this.suppressCors && CorsUtils.isCorsRequest(request)) {
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowedOrigins(new ArrayList<>(this.allowedOrigins));
		config.addAllowedMethod("*");
		config.setAllowCredentials(true);
		config.setMaxAge(ONE_YEAR);
		config.addAllowedHeader("*");
		return config;
	}
	return null;
}
 
Example 27
Source Project: oneplatform   Source File: SwitchEnableCorsFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	RequestContext ctx = RequestContext.getCurrentContext();
	// /api/tax/list -> tax 
	String routePath = request.getRequestURI().substring(configManager.getContextpth().length() + 1);
	if(routePath.contains("/"))routePath = routePath.substring(0,routePath.indexOf("/"));
	if(ctx != null){
		ctx.put(PlatformConfigManager.CONTEXT_ROUTE_NAME, routePath);
	}
	
	Pattern pattern = configManager.getCorsEnabledUriPattern(routePath);
	boolean corsEnabled = pattern != null && pattern.matcher(request.getRequestURI()).matches();
	
	if (corsEnabled && CorsUtils.isCorsRequest(request)) {
		CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
		if (corsConfiguration != null) {
			boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
			if (!isValid || CorsUtils.isPreFlightRequest(request)) {
				return;
			}
		}
	}

	filterChain.doFilter(request, response);
}
 
Example 28
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match.
 */
@Override
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	MediaType contentType;
	try {
		contentType = StringUtils.hasLength(request.getContentType()) ?
				MediaType.parseMediaType(request.getContentType()) :
				MediaType.APPLICATION_OCTET_STREAM;
	}
	catch (InvalidMediaTypeException ex) {
		return null;
	}
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<ConsumeMediaTypeExpression>(this.expressions);
	for (Iterator<ConsumeMediaTypeExpression> iterator = result.iterator(); iterator.hasNext();) {
		ConsumeMediaTypeExpression expression = iterator.next();
		if (!expression.match(contentType)) {
			iterator.remove();
		}
	}
	return (result.isEmpty()) ? null : new ConsumesRequestCondition(result);
}
 
Example 29
Source Project: lams   Source File: HeadersRequestCondition.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns "this" instance if the request matches all expressions;
 * or {@code null} otherwise.
 */
@Override
public HeadersRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	for (HeaderExpression expression : expressions) {
		if (!expression.match(request)) {
			return null;
		}
	}
	return this;
}
 
Example 30
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param request the current request
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
public ProducesRequestCondition getMatchingCondition(HttpServletRequest request) {
	if (CorsUtils.isPreFlightRequest(request)) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	List<MediaType> acceptedMediaTypes;
	try {
		acceptedMediaTypes = getAcceptedMediaTypes(request);
	}
	catch (HttpMediaTypeException ex) {
		return null;
	}
	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<ProduceMediaTypeExpression>(expressions);
	for (Iterator<ProduceMediaTypeExpression> iterator = result.iterator(); iterator.hasNext();) {
		ProduceMediaTypeExpression expression = iterator.next();
		if (!expression.match(acceptedMediaTypes)) {
			iterator.remove();
		}
	}
	if (!result.isEmpty()) {
		return new ProducesRequestCondition(result, this.contentNegotiationManager);
	}
	else if (acceptedMediaTypes.contains(MediaType.ALL)) {
		return EMPTY_CONDITION;
	}
	else {
		return null;
	}
}