MVC AntiForgeryToken cookie missing in browser before login. - asp.net-mvc-4

Application is accessed under https:// url.
In MVC application we have added ##Html.AntiForgeryToken() on cshtml razor engine and ValidateAntiForgeryToken on controller.
It all worked fine for after login pages, but with login page it goes to application error as there was no cookie seen on browser before logging into the system.
Went through several forums, articles and even added the following piece of code in global.asax.
AntiForgeryConfig.CookieName = "CSRF";
AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
//AntiForgeryConfig.RequireSsl = true; -- only for https.
Even wrote a simple SetCookie in get method of login page, that cookie doesn't show up on browser. What could be the problem.
Why i was able to see the below in cshtml but controller doesn't accept the post with antiforgeryvalidation before login.
.
Any help would be greatly appreciated

Related

Razor Pages - HTTP Error 400 (Invalid Anti Forgery Token) when idle the web site

I'm developing a web site in Blazor Server Side. My Login page is a Razor Page and everything works as expected, but if a user leaves their browser open for a period of time around 20 minutes and then performs the login they get an Http Error 400. I think it is for the Anti Forgery Token, because if you delete the cookie ".AspNetCore.Antiforgery" you got the same error. What should I do to solve this issue? What do you recommend?
If the application is being hosted in IIS I recommend setting Load User Profile = True in the application's app pool > Advanced settings menu. I had a similar issue in the past and I noticed every time the application restarted in IIS the keys were not persisted and any form opened before the restart is useless. However as soon as I changed the setting the key persisted. https://codeshorts.com/ASP-NET-Core-IIS-Invalid-Anti-Forgery-Token-Error-400
This also seems to have been an issue with Azure hosted apps
https://stackoverflow.com/a/52302702/1843966
You can try to apply IgnoreAntiforgeryToken Attribute to LoginModel class to skip antiforgery token validation, like below.
[AllowAnonymous]
[IgnoreAntiforgeryToken]
public class LoginModel : PageModel
{
//...
Note: normally, disabling antiforgery token validation is not recommended. But in this thread, applying it to LoginModel (user login functionality) should be fine.
I found this approach using code so you can catch the exception if it does fail

AbpSession.UserId return null after login

I used Asp.Net Zero (Asp.Net Boilerplate framework) in a project.
There is a problem on Chrome (some computers) and Internet Explorer (all computers) :
When authenticating with login information, the response returns with success.
But when redirect from login page to the app, auth-guard.service check current login information. This time, the application tries to get UserId from AbpSession and returns null, also page redirect to the login page again, although login was succeed.
Can anyone help me? Thanks.
Check your browsers whether they accept cookies.
When you login, you have to see the at least Abp.AuthToken and enc_auth_token cookies. You can use EditThisCookie editor to see your current cookies easily.

ASP.NET Core app under IIS - can't stay logged in

I am nearly finished migrating an ASP.NET Core app from RC1 to 1.1.0. Everything is working great until I try to publish the app and host it in IIS.
In a debugger, or working directly from Kestrel, I have no problems. I can reach my site, login, and interact with it normally.
Under IIS, however, I can load the site and am correctly redirected to my login page, but despite logging in with the correct credentials, I am redirected back to the home page and am not logged in. I can repeat this cycle over and over - I am authenticating, but some part of the IIS/Core middleware isn't keeping me logged in.
My site is using ASP.NET Core Identity which is largely unchanged from the RC1 default VS project template.
AccountController:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var signInStatus = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);
if (signInStatus.Succeeded)
return RedirectToLocal(returnUrl);
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Unfortunately, I can't debug this, because the VS debugger hooks Kestrel, and when hosting natively from Kestrel this problem doesn't exist. I'm not able to attach my debugger to the running Kestrel process (that was launched by IIS) - I can get attached but my breakpoints will not attach.
I am certain that the method above is being called. If I enter an incorrect password, I do indeed see the "Invalid username and password" prompt. When I login "successfully", I am redirected to the original page. The problem is that after the redirect, I'm not logged in - the navbar still shows my Login button instead of the Logout button, and I can't interact with any authorized controllers.
I know this is a super vague question with little source, but I'm not sure where to even start with this one. I'm hoping someone might see what my problem is and point me in the right direction, or at least be able to suggest some steps I can take to isolate and try to debug the issue. Or, barring that, even some hints as to what information I can add to my question to give necessary details.
Thank you!
Two starting points you can try:
Install the latest Windows Server Hosting bundle on your server.
Monitor and compare traffic between the working and broken systems after you click the login button. Are you getting the Identity authentication cookie returned on the broken system similar to the working one?

Using JMeter with ASP .NET MVC 4 web app returns 500 status error when logging into web app. Why?

I'm using JMeter to load test my web app. I created two HTTP Requests, one visit login page and the other, log into my account. The visit login page HTTP request works fine and returns 302 Found status. JMeter displays the login page and there 0% errors on that page.
However, when I try to login into my account using the POST Data I retrieved from Firebug POST, it doesn't work and returns a 500 status error.
I am having difficulty getting the logging into my account feature to work. I have tried to send a POST request with the following:
1) __RequestVerificationToken
2) languageDropDown (My web app requires it)
3) UserName
4) Password
but I am still getting the error.
I followed this tutorial as it's the only one on ASP.NET MVC web apps...
http://build-failed.blogspot.pt/2012/07/load-testing-aspnet-mvc-part-3-jmeter.html
But I didn't do the feedback form data because I don't need it. Just grab the general concepts and regular expression from that webpage and tried it on my app but it fails.
Why? How do I fix it?
Is it because I have cookies to store session and only unique users can login my web app at one time? I did add a cookie manager though.
BTW, this is on a deployed web application (not localhost).
Some photos, I blocked out all sensitive information (sorry) and some of the token's (Just in case?)
Are you sure you have static authentication token? May it dynamic?
Look at second video that deals with token at 5:37 min to understand how to extract dynamic authentication token.
Exept HTTP Cookie manager, try to add HTTP Cache manager

ASP.NET Identity using WebApi & External Login

Once again I am stuck! I am trying to implement a secure WebApi service with ASP.NET Identity using Individual Account. The WebApi service will be consumed by a mobile app developed with phonegap. My phonegap app uses facebook and twitter for login and I have implemented that on the client perfectly.
I have created a SPA project form the visual studio template and I have tested the login process monitoring the HTTP requests with fiddler and chrome dev tools. I have tried the following requests using postman
GET: http://localhost:49577/api/Account/ExternalLogins?returnUrl=/&generateState=true
RESPONSE:
[{
"Name": "Facebook",
"Url": "/api/Account/ExternalLogin?provider=Facebook&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A49577%2F&state=jpePf27F3ufkCCEldFdoOVMEGBGTEO1CrRdUQ3bHEP01",
"State": "jpePf27F3ufkCCEldFdoOVHSGBGTEO1CrRdUQ3bHEP01"
}]
and then I call
GET: http://localhost:49577/api/Account/ExternalLogin?provider=Facebook&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A49577%2F&state=jpePf27F3ufkCCEldFdoOVMEGBGTEO1CrRdUQ3bHEP01
which calls GetExternalLogin method of AccountsController. This then returns an instance of ChallengeResult when the user isn't authenticated.
This is where I an stuck.
Q1: ChallengeResult forces a 301 redirect to facebook login page with some querystring parameters. I don't want this, I want it to give me the parameters but let me handle the logging in my ajax request. I have tried commenting out this line of code
Request.GetOwinContext().Authentication.Challenge(LoginProvider);
but I end up getting a 401 with nothing else, how can I control what the response from ChallegeResult?
Q2. Also, I cannot quite figure out what next from here, after I get an access token from facebook, what webapi end point should I call for instance if I have already obtained the access token, what should I be passing to it?
I have googled all day but I cannot find anything that answers my question. Any help would be appreciated.
Thanks
UPDATE:
Regarding Q2; I have figured out the next step and that's
GET: http://localhost:49164/signin-facebook?code=...&state=...
This returns another 302 which redirects to
http://localhost:49164/api/Account/ExternalLogin?provider=Facebook&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A49164%2F&state=7oGPd37EA-nmtXPtYEQ40qnretDeKjbPEM1gNkb2DuM1
which in turn returns another 302 which then redirects to
http://localhost:49164/#access_token=...
So how do I handle all there redirects from a mobile non browser client?
UPDATE
I am trying to find the controller action that handles
http://localhost:49164/signin-facebook?code=...&state=...
Can anyone help?
UPDATE
I have since posting this question learned alot about the facebool login flow, which maybe I should have done before!
I still have one question but I have created a different question for that here to keep down the clutter
The answer to this question is a very detailed one. So to make it easier, I am going to point you to a sample which shows you how you can have a SPA app and connect different clients (phone, tablets etc) and login with Social logins such as Facebook etc
https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/Todo/ReadMe.txt