0
votes

I've got a local site running MVC5 WebApi 2. I have the default AccountController on there, and I've got a WebApi controller I've locked down with the [Authorize] attribute so I need to be logged in. What I want to do is connect to it via UWP with authorization first.

The default Login POST method looks like this:

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

If I try to use Postman to POST to that URL I get an error on anti-forgery token. Just wondering what I need to do both on the Web Api 2 end and the UWP end to get it going. On the UWP end I'm trying to set this up via a Windows.Web.Http.HttpClient on the login button click in my XAML. Don't have code for that yet as I was testing in Postman first to see what I need to do to get a connection. Do I need to add a method on AccountController that bypasses the anti-forgery token and just takes a username/password on a POST method, or is that not recommended?

So my UWP just has a textbox for username and password, I want to connect to my web server via

1

1 Answers

0
votes

You need to add the 'RequestVerificationToken' header to the postman request to test. You will also need to implement your own way to actually get the token from the api for testing. Something like:

[HttpPost]
[AllowAnonymous]
public IActionResult GetToken()
{
   string cookieToken, formToken;
   System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
   return this.Ok(cookieToken + ":" + formToken);
}

For you application, you will need to add the equivalent of Razors @Html.AntiForgeryToken() to the page generation, and make sure you add the header the same as in testing to the requests.