Spring Security - 所有JQuery Ajax发布请求都返回404

时间:2015-03-11 11:50:59

标签: jquery ajax spring spring-mvc spring-security

我的$.ajax POSTGET都工作正常,但只要我将Spring security 3.2.6集成到我的项目中,POST ajax请求就停止了没有登录任何问题。

弹簧security.xml文件

<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://www.springframework.org/schema/security"
             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-3.2.xsd">

    <!--Permit all Web resources to bypass proxy-->
    <http pattern="/js/**" security="none"/>
    <http pattern="/css/**" security="none"/>
    <http pattern="/fonts/**" security="none"/>
    <http pattern="/images/**" security="none"/>

    <http auto-config="true" use-expressions="true" >

        <intercept-url pattern="/login" access="isAnonymous()"/>

        <intercept-url pattern="/workflow**" access="hasRole('ROLE_WORKFLOW_ADMIN')"/>
        <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_WORKFLOW_ADMIN','ROLE_DMS_ADMIN')"/>

        <access-denied-handler error-page="/403"/>

        <form-login
                login-page="/login"
                default-target-url="/dashboard"
                authentication-failure-url="/login?error"
                username-parameter="username"
                password-parameter="password"/>

        <logout invalidate-session="true" logout-success-url="/login?logout"/>

        <csrf/>
    </http>

    <!-- Select users and user_roles from database -->
    <authentication-manager>
        <authentication-provider ref="daoAuthenticationProvider"/>
    </authentication-manager>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="authService"/>
    </beans:bean>


</beans:beans>

Web.xml中

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/error</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error</location>
    </error-page>

</web-app>

修改


我尝试访问的网址是

  

http://localhost:8080/ADMIN/workflow/sample-ajax

对于弹簧安全来说,这可能是件好事吗?

4 个答案:

答案 0 :(得分:11)

最后经过三天痛苦的日子,我发现了问题,男孩就是傻瓜。

问题在于我在spring security中启用了csrf保护。这导致我的帖子请求被禁止触发access-denied-handler错误页面,因为我没有将access-denied-handler映射到"/403"错误页面,如下所示,我的{{1}被http 403/401

掩盖了
http 404

所以简短

  1. 将您的<access-denied-handler error-page="/403"/> 错误页面映射到有效的网址
  2. 如果您使用csrf保护,那么请务必确保在ajax post请求中传递它们
  3.   

    $ .ajax({method:'POST',url:'/ ajax',数据:   {“$ {_ csrf.parameterName}”:“$ {_ csrf.token}”}});

答案 1 :(得分:4)

当你实现spring security 4时,还有一个必须参考的情况,一个需要表单按钮(不是“a href”)。

https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/#ajax-requests

A&GT;发送表单发布请求:隐藏在 登录/注销按钮

中的输入类型
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

B个对于AJAX post请求,在taglib声明之后在JSP页面中添加以下内容。

<meta name="_csrf" content="${_csrf.token}" />
<meta name="_csrf_header" content="${_csrf.headerName}" />

以及在jsp任何地方关闭 body 标记的部分,因为它“准备就绪”

<script type="text/javascript">
$(function() {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});
 </script>

它应该工作! 如果您仍然存在CORS问题,请参阅下文。 http://www.html5rocks.com/en/tutorials/cors/

答案 2 :(得分:1)

使用带有Spring MVC,Spring Security 5和Thymeleaf 3.0.11的Spring Boot 2.2.1的替代解决方案

我很高兴终于找到了解决这个问题的方法,我也想在这里分享它:

问题

就我而言,这是对有效URL的$ .ajax POST请求,返回404错误状态(未找到)。

@Mushtaq Jameel解释说,问题的原始原因是 csrf ,从Spring Security 4起,默认启用了该功能source)。

解决方案

我还没有测试@Mushtaq Jameel提出的建议,但是这个优雅的快速解决方案对我有用:

AJAX代码:

  $.ajax({
                type: "POST",
                url: "/",
                data: $('.cd-signin-modal__form.sign-up').serialize(),  // <- FIX    
                success: // some code
                error: // some code
            });

        }

换句话说,解决方案是在HTML表单本身上调用.serialize()方法。

然后发生的情况是,在POST请求中自动添加了 _csfr令牌作为其他表单参数:

enter image description here

这再次是由于在较新版本的Spring Security中默认启用了csrf(here,其中提到此隐藏表单参数是自动添加的。)

然后我的Spring MVC控制器接受如下形式:

 @PostMapping("/")
    public String createUser(@Valid @ModelAttribute User user, @Valid @ModelAttribute UserDetails userDetails, BindingResult errors) {
        if (errors.hasErrors()) {
            // handle errors
        }
        //  persist objects in database
        return "index";
    }

答案 3 :(得分:0)

您是否尝试使用普通的http请求发布使用Spring安全性,您必须使用特定的变量名称集来进行谷歌搜索。

同时检查我们是否可以使用AJAX将发布请求发送到受限制的URL。