反伪造令牌Web Api 2 [英] Anti-Forgery Token Web Api 2

查看:96
本文介绍了反伪造令牌Web Api 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web Api网站有一个AccountController,它使用默认的登录实现:

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);
    }
}

这对于Web来说很好用,但是如果我使用的是UWPXamarin之类的客户端应用程序,那么如果我想不使用WebView进行登录就成为一个问题,因为它看起来像Web Api之所以与Web耦合,是因为它依赖于在View中生成并在提交后重新发布的anti-forgery令牌.假设我希望该客户端应用程序像我看到的大多数移动应用程序一样,仅使用文本框和一个提交按钮进行登录.他们通常不会弹出WebView.

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.

是创建另一种无需使用防伪令牌登录用户的方法的唯一解决方案吗?这似乎有点混乱,并且没有很好地遵循DRY原则,更不用说潜在的安全风险了.

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.

推荐答案

为此的答案是,通过对/Token端点进行POST并重写ApplicationOAuthProvider来允许客户端访问,从而完全绕过反伪造令牌.有关详细信息,请参见以下stackexchange:

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]在以下情况下返回错误登录

这篇关于反伪造令牌Web Api 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆