How to use @Html.AntiForgeryToken() post a ajax submit to server ?
@Daniel15
By ReactJs.Net, server Action has marked with [ValidateAntiForgeryToken] attribute. on server-rendering.
I think you'll have to pass the token as a prop to your React component.
@Daniel15
but @Html.AntiForgeryToken() will generate a input tag named __RequestVerificationToken, not a clean token value, like this: how to insert it to my component? render: function () { return (
cannot post html tag text here! oh...
@Daniel15 l am following https://reactjs.net/getting-started/tutorial.html. could you update this arcticle for append a step with "How to use AutoValidateAntiforgeryToken" attribute in ReactJs.Net on Server-side rendering. Another question is i want to know how to dependence .NET Core not .NET Framework.
There are a couple things you could try:
- You can render the anti forgery token into an element at the top of every page, and then reference the element via an ID selector
- Set a special header, such as "X-Requested-With", with every form post, and refuse to process the request if that header is missing. This can help avoid CSRF attacks but is not foolproof (old versions of Flash could sidestep this check)
@dustinsoftware OK, thanks
We had to incorporate AntiForgeryToken as well. We ended up doing the following:
1 Render the antiForgeryToken hidden input to the view using razor
@Html.AntiForgeryToken()
2 Create an ajax service that wraps $.ajax() and adds the value of the antiForgeryToken to all your ajax requests
module.exports = (function () {
this.ajax = function (options) {
var settings = options,
tokenElements = document.getElementsByName("__RequestVerificationToken");
if (tokenElements.length) {
settings.data = settings.data || {}; // make sure data property is available even if it's not passed in
settings.data.__RequestVerificationToken = tokenElements[0].value;
}
return $.ajax(settings);
}
})()
3 Import the ajax service into your react components that use ajax
var ajaxService = require('./ajaxService');
4 Use like you would normally use $.ajax() but with ajaxService.ajax() instead.
ajaxService.ajax({
url: 'some/url',
data:{},
type: 'POST'
})
.success(...)
.error(...);
I've had success passing in the antiForgeryToken through props:
@Html.React("SomeComponent", new
{
antiForgeryToken = Html.AntiForgeryToken().ToHtmlString(),
}
Then in the component I'll do something like:
const antiForgeryTokenContainer = document.createElement('div');
antiForgeryTokenContainer.innerHTML = this.props.antiForgeryToken;
const antiForgeryToken = antiForgeryTokenContainer.firstChild.value;
Unfornuately, @Imundy 's solution does not work with ASP.NET Core as Html.AntiForgeryToken() does not have a ToHtmlString method or any similar one.
For ASP.NET Core the optimal solution is to aquire the token via IAntiforgery.GetAndStoreToken.
Sample
Assume we have a method with ValidateAntiForgeryAttribute:
public class AccountController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model)
{
/* Login Logic */
}
}
Use IAntiforgery within the Index.cshtml file. This will also set http-only cookie required for antiforgery validation.
@model HomeViewModel
@inject IAntiforgery Antiforgery
@Html.React("Home", new
{
antiforgeryToken = Antiforgery.GetAndStoreTokens(Context).RequestToken
})
Now you can use the token within your react app and pass it either as form data or Header for fetch requests:
// Use as form data input
function Home({ antiforgeryToken }) {
return (
<form action="/Account/Login" method="post">
<input type="hidden" name="__RequestVerificationToken" value={antiforgeryToken} />
{/* More form input */}
</form>
)
}
// Or use as Header for fetch
class Home extends React.Component {
onPostSomething() {
fetch('https://my-web.com/Account/Login', {
method: 'POST',
headers: {
'RequestVerificationToken': this.props.antiforgeryToken,
/* more headers */
},
body: {/* formdata or json or whatelse */}
}).then( /* continue ... */ )
}
}
Closing issues older than a year, please re-open if you think this is still relevant.