0

I have MVC 5 application that uses Form Authentication (the same as in default MVC 5 project template). The same project contains WebAPI 2.2 controller that provides some API the application uses.

I would like to have two type of access to the API by using Bearer Tokens. The API will be invoked via javascript. I added code to do that using http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api.

The problem is that the example code gets token by making call to separate API and providing username and password. What I would like to achieve is to return Bearer Token after the user successfully logs in into MVC application and not by making another call in javascript.

Is this possible ?

Update: I would like to return token in Login action of Account controller by using header. However probably because of redirections the header is discarded.

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    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 you are Web API and MVC5 application share same authentication logic then you can generate token at the time of login in mvc5 application and later you can use with web api as well. – dotnetstep Dec 09 '14 at 04:23

1 Answers1

0

You can use Oauth authentication thereby which you can generate an access token and can be used the same for further requests to the web API. This access token can be saved in db or somewhere for using in future requests.

Hamid Narikkoden
  • 851
  • 5
  • 12