The required anti-forgery cookie “__RequestVerificationToken” is not present - asp.net-mvc

As I have deployed my newly created Asp.Net MVC web application to the server, I am facing the subject error, upon submitting a sign-up form. It is working fine in my local environment.
In my controller's action method, I have set the attribute to validate the token as shown below:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
////
}
And in my view, I have set as:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
}
////
)
One more thing is that I have enabled SSL on my project properties. I have also added <httpCookies httpOnlyCookies="true" requireSSL="true"/> in my web.config file.
While inspecting, I can see the hidden element <input name="__RequestVerificationToken" type="hidden" value="blaa blaa>", but i cannot see any cookie present there.
After hours of troubleshooting, I am still unable to find a solution to this problem. I am always getting error The required anti-forgery cookie "__RequestVerificationToken" is not present.
How to get rid of this?

I myself has find the answer to this question. In my case, as I have set SSL to true, I need to have a security certificate. So, I purchased and configured the certificate on my hosted site and the error has gone.

Related

The required anti-forgery cookie "__RequestVerificationToken" is not present.

The required anti-forgery cookie "__RequestVerificationToken" is not present.
I have added in cshtml and in Controller also
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
//some code
}
[HttpGet]
[ValidateAntiForgeryToken]
public ActionResult Index()
{
using (var db = new SampleEntities())
{
return View(db.Rfps.ToList());
}
}
In my case, I had this in my web.config:
<httpCookies requireSSL="true" />
But my project was set to not use SSL. Commenting out that line or setting up the project to always use SSL solved it.
The issue is because you are using a ValidateAntiForgeryToken attribute on a GET request.
You don't need to use this attribute for GET actions. Look here for more information:
In my case, it was because I ran another Asp.Net website before. So the cookies could not match for localhost.
I cleared my cookies (just for localhost) and everything is fine now.

mvc5 Additional information: 'object' does not contain a definition for 'Action'

I get:
'object' does not contain a definition for 'Action'
excepiton in my "_ExternalLoginsListPartial" view but I don't understand why because in Login view I call:
#Html.Partial("_ExternalLoginsListPartial", new { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
And when I look into the Model in debugger it definaltely contains "Action".
Can anyone help me understand that?
Actually my site was running but today I started to edit "ManageUserViewModel" so that I can store some user specific settings in it. After that I always get this exception although I already reverted my changes...
The code below makes my website run again:
//string action = Model.Action;
//string returnUrl = Model.ReturnUrl;
string action = "ExternalLogin";
string returnUrl = "/myTime/en/Manage";
using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }))
{
#Html.AntiForgeryToken()
<div id="socialLoginList">
<p>
#foreach (AuthenticationDescription p in loginProviders)
{
<button type="submit" class="btn btn-default" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType" title="Log in using your #p.Caption account">#p.AuthenticationType</button>
}
</p>
</div>
}
UPDATE:
I'm able to reproducte the problem. As mentioned above I tried to change "ManageUserViewModel" so that the user can set some settings. Since I only use Google login I removed the password stuff for the model. To reproduce the exception comment out everything in ManageUserViewModel (make it an empty class).
Then comment out everything in Manage:
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
// If we got this far, something failed, redisplay form
return View(model);
}
and then comment in:
app.UseGoogleAuthentication();
in StartupAuth.cs
And you get the exception when you click the google login button.
You can use the default MVC5 template and just do the steps described above to reproduce this...
I'm not sure if it is the wrong place to let my user store his settings. However, the screenshot below is definately giving me wrong information...
UPDATE2:
You don't have to edit Manage function in AccountController. It is enough to make “ManageUserViewModel” empty.
Cheers,
Stefan
The fact that it exists in the debugger is meaningless. The debugger exposes the object and all it's properties without knowing or caring about it's type. The problem you're having in your view is that you don't have a model definition, and because of that, your "model" is an object. The Object type truly does not have a property or method named Action, so you get the error.
The best solution is to simply specify your model as the actual type you're working with. Then you get intellisense and all the other goodness that comes from being strongly-typed. The alternative, is to cast Model to dynamic, but that's really nasty.
I encountered this exact error on this exact line because I had enabled Twitter as an authorization source with bogus key and secret values.
When I commented that section out in StartupAuth.cs, the application worked as expected.

asp.net mvc User.Identity.Name is empty after posting any page

I have written some simple code to illustrate the problem.
The controller code:
public ActionResult Edit()
{
string un = User.Identity.Name;
return View();
}
[HttpPost]
public ActionResult Edit(int? dummy)
{
string un = User.Identity.Name; // <-- here it's empty string
return View();
}
The Edit.cshtml view code:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<input type="submit" value="Submit" />
}
The User.Identity.Name is not empty after I log in and I go to the Edit page.
But after I submit the Edit page (I make a HTTP POST) the User.Identity.Name becomes empty string and remains empty string no matter what page I access.
In Web.config I have:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
This sounds like a strange problem, and though I can't give you an answer yet, this might help.
FormsAuthentication works by setting a cookie on the browser called .ASPXAUTH. After you sign in, inspect the cookies in your browser and look for it. Also, you can inspect the Request property in the controller action methods to look for that cookie. It will be a weird-looking encoded value. You can also use something like Fiddler2 to make sure that the cookie is being sent when you post the form.
I have run into this problem before, but it had to do with cross-domain requests and machineKey mismatch problems. If both your Edit actions are in the same controller / project / URL / web.config, then perhaps something in the pipeline is removing the cookie, or reconfiguring your User principal during POST requests..? You aren't using OWIN anywhere in the project, right? And there are no global filters other than HandleErrorAttribute?

MVC 4 Anti-Forgery Error with Login

I have an MVC 4 web application with ELMAH running in the background to help me keep track of any errors occurring on the website. I have noticed a good few errors happening stating the following
System.Web.Mvc.HttpAntiForgeryException: The required anti-forgery
form field "__RequestVerificationToken" is not present.
The majority of these errors seem to be happening when a user attempts to log into my website. To be honest, I just used the out of the box MVC 4 Visual Studio login View for this, ie, my View has the following
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
//textboxes for username and password
//login button
}
And then my Account Controller with Login Action
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && _accountService.Logon(model.Email, model.Password,false))
{
}
}
Do you think anything looks wrong with this code? I am not sure how to get rid of these errors.
Any feedback or advice would be appreciated.
Thanks.
I've had a user report the same problem and we've identified that it happens when they click the login button twice.
I assume the problem is that logging in changes the token, but when the form is resubmitted it has the old token. One solution would be to disable to login button so the user can only submit the form once.
That's not perfect though, as the login may time out or something and they won't be able to try again without reloading the page, so I'm currently looking for better solutions.

AntiForgeryToken deprecated in ASP.Net MVC 4 RC

I just installed ASP.Net MVC 4 RC to replace ASP.Net MVC 4 beta. When trying to run an existing application I'm getting an error message that AntiForgeryToken has been deprecated. Here's my code:
using (Html.BeginForm("", "", FormMethod.Post, new { id = "MonthElectionForm" }))
{
#Html.AntiForgeryToken("AddEditMonthElection")
}
---- UPDATE ---
ASP.Net MVC 4 RC has made the Salt property obsolete for ValidateAntiForgeryToken attribute and AntiForgeryToken html helper. So, now my code looks like this:
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreateCompany(CompanyDataEntryViewModel modelData)
{...}
form:
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "CreateCompanyDataEntryForm" }))
{
#Html.AntiForgeryToken()
...
}
Looking at generated HTML, AntiForgeryToken still generates a hidden field and provides an encrypted value. My action still works too. But I've lost the ability to designate a key to use in the encryption process. I'm not too sure how the process works, but before I can tell I was setting the salt value on the action and on the form. The values had to match in order for the action to accept the post. So, how do you set the salt value now? I think it has something to do with AntiForgeryConfig AdditionalDataProvider but I cannot find anything googling on how to use AntiForgeryConfig AdditionalDataProvider. Please help.
Thanks
Setting the salt parameter is unnecessary and didn't provide any additional protection, so we removed support for it.
Please see my response at How to choose a salt value for ValidateAntiForgeryToken for more information.

Resources