我试图在Spring Security 4.2.3.RELEASE上启用CORS。 弹簧mvc.xml
<mvc:mapping path="/rest/**"
allowed-origins="*"
allowed-methods="GET, POST, HEAD, OPTIONS, PUT, DELETE"
allowed-headers="Content-Type, X-Requested-With,accept, Origin,Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"
exposed-headers="Access-Control-Allow-Origin,Access-Control-Allow-Credentials"
allow-credentials="false"
max-age="10" />
</mvc:cors>
弹簧security.xml文件
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/rest/**" use-expressions="true" entry-point-ref="unauthorizedEntryPoint" create-session="stateless">
<csrf disabled="true"/>
<cors/>
<custom-filter before="FORM_LOGIN_FILTER" ref="jwtAuthenticationFilter"/>
</http>
尝试部署时: 引起:org.springframework.beans.factory.BeanCreationException:无法创建CorsFilter
答案 0 :(得分:0)
我正在解决类似的问题。我尝试了几种方法,如果有人需要,这是最合适的设置。
SpringSecurity:4.2.0.RELEASE。所有服务器的API调用都以/api/
路径为前缀
Spring安全上下文:
<http use-expressions='true'>
<!-- unrelated code skipped for brevity -->
<cors configuration-source-ref="corsSource"/>
</http>
<beans:bean id="corsSource" class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
<beans:property name="corsConfigurations">
<util:map>
<beans:entry key="/api/**">
<beans:bean class="org.springframework.web.cors.CorsConfiguration">
<beans:property name="allowCredentials" value="true"/>
<beans:property name="allowedHeaders">
<beans:list>
<beans:value>Authorization</beans:value>
<beans:value>Content-Type</beans:value>
</beans:list>
</beans:property>
<beans:property name="exposedHeaders">
<beans:list>
<beans:value>Account-Locked</beans:value>
<beans:value>Account-Disabled</beans:value>
<beans:value>Bad-Credentials</beans:value>
</beans:list>
</beans:property>
<beans:property name="allowedMethods">
<beans:list>
<beans:value>POST</beans:value>
<beans:value>GET</beans:value>
<beans:value>OPTIONS</beans:value>
</beans:list>
</beans:property>
<beans:property name="allowedOrigins" value="http://localhost:3000"/>
</beans:bean>
</beans:entry>
</util:map>
</beans:property>
</beans:bean>
在我的 dispatcher-servlet.xml
中<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="http://localhost:3000"
allow-credentials="true"
allowed-methods="GET, OPTIONS"
/>
</mvc:cors>
记住要更改allowed-origins
和allowedHeaders
(=允许客户端附加到请求头),exposedHeaders
(=允许服务器附加到其响应头)和allowedMethods
。
要保留授权用户的会话,我必须在Spring Security配置中添加allowCredentials
属性,并在JavaScript调用中将withCredentials
标志设置为true
。我使用了 axios ,因此,如果您使用其他库,则标记的名称可能会有所不同。