首页 > 解决方案 > 调用 spring security /login 时未设置 CORS 标头

问题描述

我的 spring security 4.2 CORS 配置需要一些帮助。

调用 spring 安全登录页面http://localhost:8080/login时,未在预检请求中设置 CORS 标头。

调用不同的 URL 时,CORS 标头设置正确。


浏览器控制台错误消息:

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

铬合金: 在此处输入图像描述

弹簧安全 4.2

    <!-- Main security configuration -->
    <security:http entry-point-ref="mainEntryPoint">
        <security:cors configuration-source-ref="corsSource"/>

        <!-- Handle CORS (preflight OPTIONS requests must be anonymous) -->
        <security:intercept-url method="OPTIONS" pattern="/**" access="isAnonymous()"/>

        <security:intercept-url pattern="/main/**" access="hasRole('USER')"/>
        <security:intercept-url pattern="/**" access="denyAll"/>

        <security:custom-filter position="LOGOUT_FILTER" ref="mainLogoutFilter"/>

        <security:csrf disabled="true"/>
    </security:http>

   (...)

    <bean id="corsSource" class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
        <property name="corsConfigurations">
            <map>
                <entry key="/**">
                    <bean class="org.springframework.web.cors.CorsConfiguration">
                        <property name="allowCredentials" value="true"/>
                        <property name="allowedHeaders" value="*"/>
                        <property name="allowedMethods" value="*"/>
                        <property name="allowedOrigins" value="http://localhost:4200"/>
                        <property name="maxAge" value="86400"/>
                    </bean>
                </entry>
            </map>
        </property>
    </bean>

标签: springspring-mvcspring-security

解决方案


我在另一个文件中发现登录路径配置被覆盖。所以这个问题是我的项目特有的。

<security:http pattern="/login">
</security:http>

我留下一个工作配置的例子。


推荐阅读