I'm developing a Web App with Asp .Net MVC 5 and this have normal ASP.NET Identity, but now I developed a Mobile App and I need authenticate users with my ASP app.
I'm tried to make an AJAX request to my Login method but the server response an exception: "Validation of the provided anti-forgery token failed. The cookie "__RequestVerificationToken" and the form field "__RequestVerificationToken" were swapped." because I have [ValidateAntiForgeryToken] decorator, and I think that ASP .NET Identity has any other way to authenticate, but I don't know.
This is my login method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModdel model, string ReturnUrl)
{
if (ModelState.IsValid)
{
Employer user = await _employerService.GetByCredentialsAsync(model.Email.Trim(), model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
Response.StatusCode = (int)HttpStatusCode.OK;
}
else
{
Employer existingEmail = await _employerService.GetByUsernameAsync(model.Email);
if (existingEmail == null)
{
ModelState.AddModelError("", "El usuario no está registrado. Regístrate o intenta ingresar con un nuevo usuario");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { statusCode = 400, message = "El usuario no está registrado. Regístrate o intenta ingresar con un nuevo usuario", Success = "False" });
}
else
{
ModelState.AddModelError("", "Contraseña inválida. Intenta de nuevo");
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json(new { statusCode = HttpStatusCode.Unauthorized, Success = "False" });
}
}
}
if (string.IsNullOrWhiteSpace(ReturnUrl))
ReturnUrl = Url.Action("Index", "Home");
return Json(new { statusCode = HttpStatusCode.OK, returnUrl = ReturnUrl });
}
And this is my ConfigureAuth:
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
//Custom provirder create to read language fomr URL
CookieAuthenticationProvider provider = new CookieAuthenticationProvider();
var originalHandler = provider.OnApplyRedirect;
provider.OnApplyRedirect = context =>
{
var mvcContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(mvcContext);
//Get the current language
RouteValueDictionary routeValues = new RouteValueDictionary();
//Reuse the RetrunUrl
Uri uri = new Uri(context.RedirectUri);
string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);
routeValues.Add(Cross.Constants.ModalRouteValue, Cross.Constants.LoginModal);
//Overwrite the redirection uri
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
string NewURI = url.Action("Index", "Home", routeValues);
//Overwrite the redirection uri
context.RedirectUri = NewURI;
originalHandler.Invoke(context);
};
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Index?Modal=Login"),
Provider = provider,
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
Generally speaking your MVC application is only good for working in a browser. If you need to provide a third party with some data and that is not happening through the browser, you will need to use WebApi. And there you can use bearer token authentication for your clients.