Java 使用 ajax GET 请求 Spring 出现 403 Forbidden Error

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19091206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:00:44  来源:igfitidea点击:

403 Forbidden Error with ajax GET request Spring

javajqueryajaxspringspring-mvc

提问by Maff

I am getting a 403 forbidden-error every time I try GETa user's information from the database. Relating to my code below, every time I try request by pressing the Ajax Testbutton, It fails to run and gives me an alert, but also in the console gives me a 403 Forbidden-error. I am not sure whether it has something to do with Spring security?

403 forbidden每次尝试GET从数据库中获取用户信息时,都会收到-error 错误。关于我下面的代码,每次我通过按下Ajax 测试按钮尝试请求时,它都无法运行并给我一个警报,但在控制台中也会给我一个403 Forbidden-error。我不确定它是否与 Spring 安全有关?

Users JSP page:

用户 JSP 页面:

<table>
    <tr>
        <td>User Id</td>
        <td>Full Name</td>
        <td>Username</td>
        <td>Email</td>
        <td>Date of Birth</td>
        <td>User Authority</td>
        <td>Update </td>
        <td>Delete</td>
    </tr>
    <c:forEach var="user" items="${users}">
        <tr>
            <td><c:out value="${user.id}" /></td>
            <td><c:out value="${user.name}"/></td>
            <td><c:out value="${user.username}"/></td>
            <td><c:out value="${user.email}"/></td>
            <td><c:out value="${user.dob}"/></td>
            <td><c:out value="${user.authority}"/></td>
            <td>
                <a id="update" href="<c:url value="/viewUser"><c:param name="id" value="${user.id}"/></c:url>"><button>Update</button></a>
            </td>
            <td>
                <a id="delete" href="<c:url value="/deleteUser"><c:param name="id" value="${user.id}"/></c:url>"><button>Delete</button></a>
            </td>
            <td>
                <button class="loadUser" name="id" value="${user.id}">Ajax test</button>
            </td>
        </tr>
    </c:forEach>
</table>
 <div id="personIdResponse"> </div>
<script type="text/javascript">
    $(document).ready(function(){
        $(".loadUser").click(function(e) {
            e.preventDefault();
            var personId = +$(this).val();
            $.get('${pageContext.request.contextPath}/SDP/ajaxTest/' + personId, function(user) {
                  $('#personIdResponse').text(user.name + ', = username ' + user.username);
                })
            .fail(function(user){
                alert('Could not load user');
            });
        });
    });
</script>

User Controller class:

用户控制器类:

    @RequestMapping("/viewUser")
public String updateUser(Model model, @RequestParam(value = "id", required = false) Integer id) {

    User user = usersService.getUser(id);

    model.addAttribute("user", user);

    return "settings";
}

@RequestMapping("/ajaxTest")
@ResponseBody
public User ajaxTest(@RequestParam(value = "id", required = false) Integer id) {

    User user = usersService.getUser(id); 
    return user;
}

回答by Choinek

Check files permissions. 403 is server error, not Ajax. Try to check requested file (by file i mean url) directly.

检查文件权限。403 是服务器错误,而不是 Ajax。尝试直接检查请求的文件(通过文件我的意思是 url)。

回答by harsh

In Spring Restor other RESTimplementations (like Jersey) if there is no matching resources at server side then 403 Forbiddenis thrown by REST containers.

Spring Rest或其他REST实现(如Jersey)中,如果服务器端没有匹配的资源,403 Forbidden则由 REST 容器抛出。

You need to re-validate req-response annotations.

您需要重新验证 req-response 注释。

For example, for ajaxTestrequest try this change:

例如,对于ajaxTest请求尝试此更改:

@RequestMapping("/ajaxTest/{personid}", method=RequestMethod.GET)
@ResponseBody
public User ajaxTest(@PathVariable Integer personid) { .. }

Basically person-id doesn't look like a request parameter (which we set in GETURL), try changing to to PathVariableand if you are not sure on default method in Spring REST, explicitly define for which HTTP-Methodthis method should get invoked.

基本上,person-id 看起来不像一个请求参数(我们在 中设置GETURL),尝试更改为PathVariable,如果您不确定 中的默认方法Spring REST,请明确定义HTTP-Method应为其调用此方法。

On 403, it implies that operation not allowedor many similar reasons apart from auth failure. Take a look at http://en.wikipedia.org/wiki/HTTP_403for various possibilities.

在 上403,这意味着operation not allowed除了身份验证失败之外的许多类似原因。查看http://en.wikipedia.org/wiki/HTTP_403了解各种可能性。

回答by chege

If you are using Spring Security 3.2R1 and above try using this solution http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection

如果您使用的是 Spring Security 3.2R1 及更高版本,请尝试使用此解决方案 http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection

回答by lukyer

It is usually caused by Spring default CSRF protection.

它通常是由 Spring 默认的 CSRF 保护引起的。

If you use for example DELETE HTTP request from your JS code, it is required to send also CSRF protection headers.

例如,如果您使用来自 JS 代码的 DELETE HTTP 请求,则还需要发送 CSRF 保护标头。

It is not necessary to disable CSRF protection! Please, do not do that if not necessary.

没有必要禁用 CSRF 保护!如果没有必要,请不要这样做。

You can easily add CSRF AJAX/REST protection by:

您可以通过以下方式轻松添加 CSRF AJAX/REST 保护:

1.Adding meta headers to every page (use @layout.html or something):

1.为每个页面添加元标题(使用@layout.html或其他东西):

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

2.Customizing your ajax requests to sent these headers for every request:

2.自定义您的 ajax 请求,为每个请求发送这些标头:

$(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);
  });
});

Notice that i use thymeleaf, so i use th:content instead of content attribute.

请注意,我使用 thymeleaf,所以我使用 th:content 而不是 content 属性。

回答by Pradip Kharbuja

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.

从 Spring Security 4.0 开始,默认情况下使用 XML 配置启用 CSRF 保护。如果您想禁用 CSRF 保护,可以在下面看到相应的 XML 配置。

<security:http use-expressions="true">
           ...
   <security:csrf disabled="true" />
</security:http>