CORS过滤器在春季不起作用

Posted

技术标签:

【中文标题】CORS过滤器在春季不起作用【英文标题】:CORS Filter not working in spring 【发布时间】:2016-05-30 11:20:31 【问题描述】:

过去三天我一直在努力解决错误“跨域请求被阻止:同源策略不允许读取http://localhost:8080/demomongo/templateapp/login 的远程资源。(原因:CORS 标头“Access-Control-Allow-Origin”缺失)。 "

Here is my code kindly help.



    Login.html
    <html ng-app="LoginApp">
    <body>
    <script src="angular.min.js"></script>
    <script src="LoginApp.js"> </script>
    <div ng-controller="loginController as login">
    Username <input type="text" ng-model="username" /><br/>
    Password <input type="text" ng-model="password" /><br/>
    <button ng-click="validate()">Validate</button>
    </div>
    <br/> <a href="Reg.html">Register Me/New user</a>

    </body>
    </html>

    LoginApp.js
    (function()
    var app;
    app=angular.module('LoginApp',[]);
    app.controller('loginController',function($scope,$http)
    	var dataObj = 
    			"name" : "Java Honk",
    			"password" : "NY"
    					
    			;
    	$scope.validate = function() 
            dataObj.name=$scope.username;
            dataObj.password=$scope.password;

            
    	//if($scope.username=="sam" && $scope.password=="pwd")
           // console.log("password match");
           // else
            //console.log("username/pwd not matching");
    	$http.post('http://localhost:8080/demomongo/templateapp/login', dataObj)
                                .success(function(responseData) 
    			    $scope.responseData = responseData;
    			    console.log(responseData);
    			    ).error(function(data, status, headers, config) 
    			alert( "Exception details: " + JSON.stringify(data: data));
    			);
        
    );

    )();
CORSFilter:
    CORSFilter.java

    package com.demo.mongo.example.filter;

    import java.io.IOException;



    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.web.filter.OncePerRequestFilter;

    public class CORSFilter extends OncePerRequestFilter 
    	private static final Log LOG = LogFactory.getLog(CORSFilter.class);

    	@Override
    	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException 
    		response.addHeader("Access-Control-Allow-Origin", "*");
    		
    		if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) 
    			LOG.trace("Sending Header....");
    			// CORS "pre-flight" request
    			response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    //			response.addHeader("Access-Control-Allow-Headers", "Authorization");
                response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    			response.addHeader("Access-Control-Max-Age", "1");
    		
    		
    		filterChain.doFilter(request, response);
    	

    
Template Controller.java
    //templatecontroller.java
    package com.demo.mongo.example.controller;
    import java.util.List;

    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.util.UriComponentsBuilder;

    import com.demo.mongo.example.model.UserDetails;


    @RestController
    @RequestMapping("/templateapp")
    public class TemplateController 
    	@CrossOrigin
    	@RequestMapping(value="/login", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody String validateUser(@RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) 
    		/*UserDetails obj=new UserDetails();
    		List<UserDetails> values=obj.UserDetails(udata.getName(),udata.getPassword());
    		if(values.size()>0)
    			return "welcome udata.getName";
    		
    		else
    		
    			return "please register using registration link";
    		*/
            if(udata.getName().equalsIgnoreCase("admin") &&  udata.getPassword().equalsIgnoreCase("admin"))
            
            	return "welcome admin";
            
            else
            
            	return "password mismatch/not an admin";
            
    	
    	@CrossOrigin
    	@RequestMapping(value="/addUser", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody String addUser(@RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) 
            
            return " new user details: name "+ udata.getName() + " Email Id " + udata.getEmailid() ;
    	
    	
    
UserDetails.Java
    package com.demo.mongo.example.model;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;

    @Document
    public class UserDetails 
    	@Id
    	private String name;
    	private String password;
    	private String emailid;
    	private int contact;

    	public UserDetails()

    	public UserDetails(String name,String password,String emailid,int contact)
    		this.name=name;
    		this.password=password;
    		this.emailid=emailid;
    		this.contact=contact;
    	

    	public void setName(String name)
    		this.name=name;
    	

    	public void setPassword(String password)
    		this.password=password;
    	
    	
    	public void setEmailid(String emailid)
    		this.emailid=emailid;
    	
    	public void setContact(int contact)
    		this.contact=contact;
    	
    	public String getPassword()
    		return this.password;
    		
    	
    	public String getName()
    		return this.name;
    	
    	public int getContact()
    		return this.contact;
    		
    	
    	public String getEmailid()
    		return this.emailid;
    		
    	
    
**dispatcher-servlet.xml**
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


    	<context:component-scan base-package="com.demo.mongo.example" />
        <mvc:annotation-driven />
        
    	<!-- Factory bean that creates the Mongo instance -->
    	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
    		<property name="host" value="localhost" />
    	</bean>
    	
    	<!-- MongoTemplate for connecting and querying the documents in the database -->
    	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    		<constructor-arg name="mongo" ref="mongo" />
    		<constructor-arg name="databaseName" value="test" />
    	</bean>

    	<!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
    	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
       	<bean
    		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix">
    			<value>/WEB-INF/</value>
    		</property>
    		<property name="suffix">
    			<value>.jsp</value>
    		</property>
    	</bean>
    </beans>
web.xml
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" 
    	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	    version="2.5">

      <display-name>Archetype Created Web Application</display-name>
      
      <servlet>
    		<servlet-name>dispatcher</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<load-on-startup>1</load-on-startup>
    	</servlet>

    	<servlet-mapping>
    		<servlet-name>dispatcher</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>

    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    	</context-param>

    	

      <!-- Add this to your web.xml to enable "CORS" -->
    	<filter>
    	  <filter-name>cors</filter-name>
    	  <filter-class>com.demo.mongo.example.filter.CORSFilter</filter-class>
    	</filter>
    	  
    	<filter-mapping>
    	  <filter-name>cors</filter-name>
    	  <url-pattern>/*</url-pattern>
    	</filter-mapping>
    </web-app>
pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.demo.mongo.example</groupId>
      <artifactId>demomongo</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>demomongo Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        
        <dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-orm</artifactId>
    			<version>4.2.4.RELEASE</version>
    		</dependency>

    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>4.2.4.RELEASE</version>
    		</dependency>

    		<dependency>
    			<groupId>org.springframework.data</groupId>
    			<artifactId>spring-data-mongodb</artifactId>
    			<version>1.2.0.RELEASE</version>
    		</dependency>
    		
    		<dependency>
        		<groupId>org.springframework</groupId>
       			<artifactId>spring-web</artifactId>
        		<version>4.2.4.RELEASE</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-core</artifactId>
    			<version>2.7.1</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>org.codehaus.jackson</groupId>
    			<artifactId>jackson-mapper-asl</artifactId>
    			<version>1.9.2</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-databind</artifactId>
    			<version>2.7.1-1</version>
    		</dependency>
    		
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>servlet-api</artifactId>
    			<version>3.0-alpha-1</version>
    		</dependency>
      
      </dependencies>
      <build>
        <finalName>demomongo</finalName>
      </build>
    </project>
please help to fix which i did wrong.

【问题讨论】:

避免使用本地主机,设置主机名 【参考方案1】:

您在过滤器中设置了标题“Access-Control-Allow-Origin”。如果标题没有出现,请确保它是链接的。调试或记录它。

【讨论】:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException response.addHeader("Access-Control-Allow-Origin", ""); response.setHeader("Access-Control-Allow-Origin", ""); Pavel 正如你所说我添加了 setheader ,仍然是同样的错误。还缺少什么,请帮助 抱歉没有回答。但是你没有告诉你真的得到这个标题作为回应。如果您向服务器发送请求,是否会收到响应的标头?并考虑在 中为调度程序和过滤器使用相同的值。

以上是关于CORS过滤器在春季不起作用的主要内容,如果未能解决你的问题,请参考以下文章

用于弹簧靴的 CORS 过滤器不起作用

Zuul CORS 过滤器不起作用

Spring Security oauth2 cors 过滤器不起作用

CORS过滤在“授权”标头中不起作用[重复]

CORS 过滤器在我的 Java 应用程序中不起作用

Spring Security CORS 过滤器不起作用