Anti-Forgery Token Web Api 2

丶灬走出姿态 提交于 2020-01-12 17:52:09

问题


I have an AccountController for my Web Api site that uses the default implementation for the login:

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

This works fine for the web, but if I'm using a client app like UWP or Xamarin this becomes an issue if I want to login without using a WebView because it looks like the Web Api is coupled to the web since it relies on the anti-forgery token being generated in the View and posted back on submit. Let's say I want that client app to just uses textboxes and a submit button for the login like most mobile apps I see. They usually don't pop up a WebView.

Is the only solution to create another method which logs in the user without the anti-forgery token? That seems a bit messy and doesn't follow DRY principles very well, not to mention a potential security risk.


回答1:


The answer for this was to bypass the anti-forgery token completely by making a POST to the /Token Endpoint and overriding the ApplicationOAuthProvider to allow for client access. See this stackexchange for details:

WebAPI [Authorize] returning error when logged in



来源:https://stackoverflow.com/questions/43175734/anti-forgery-token-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!