문제

I am trying to use the token interceptor that ships with Struts in order to implement a CSRF check. However instead of using a <form /> I am making an AJAX call from within some JS:

foo.jsp:

<!DOCTYPE html>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
    <s:token />
    <script>
        var strutsToken = "<s:property value="#session['struts.tokens.token']" />";
    </script>
    <script src="bar.js"></script>
</body>
</html>

bar.js:

$.ajax({
    url: '/endpoint',
    data: strutsToken,
    dataType: 'jsonp',
    cache: true,
    success: function() { console.log('success'); },
    error: function() { console.log('failure'); }
});

I've confirmed the token value is making it into the JS variable:

> strutsToken
"N3ZLLLR2Y3QGMZP0L3UCYWI5CO5NYZEY"

Unfortunately when that AJAX request is made an invalid-token error is thrown on the server.

Is what I am attempting to do possible and if so, how?

도움이 되었습니까?

해결책

This is currently what is being requested by that $.ajax call:

GET /endpoint?N3ZLLLR2Y3QGMZP0L3UCYWI5CO5NYZEY

You need to give the token a parameter name. You also need to supply the "struts.token.name" parameter:

GET /endpoint?struts.token.name=token&token=N3ZLLLR2Y3QGMZP0L3UCYWI5CO5NYZEY

Now to make that work with the original code:

var token = {
    "struts.token.name": "token",
    "token": strutsToken
};

$.ajax({
    url: '/endpoint',
    data: token,
    dataType: 'jsonp',
    cache: true,
    success: function() { console.log('success'); },
    error: function() { console.log('failure'); }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top