title: How to store bearer tokens when MVC and Web API are in different projects
body: <p><strong>Situation:</strong>
  I have a Web API 2 project which acts as an Authorization server (/token endpoint) and a resource server. I am using the template that comes out of box with ASP.Net Web API minus any MVC reference. 
  The Start.Auth is configured as below:</p>
  
  <pre><code>public void ConfigureAuth(IAppBuilder app)
          {
              // Configure the db context and user manager to use a single instance per request
              app.CreatePerOwinContext(ApplicationDbContext.Create);
              app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
  
              // Enable the application to use a cookie to store information for the signed in user
              // and to use a cookie to temporarily store information about a user logging in with a third party login provider
              app.UseCookieAuthentication(new CookieAuthenticationOptions());
              app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  
              // Configure the application for OAuth based flow
              PublicClientId = "self";
              OAuthOptions = new OAuthAuthorizationServerOptions
              {
                  TokenEndpointPath = new PathString("/Token"),
                  Provider = new ApplicationOAuthProvider(PublicClientId),
                  AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
                  AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                  // In production mode set AllowInsecureHttp = false
                  AllowInsecureHttp = true
              };
  
              // Enable the application to use bearer tokens to authenticate users
              app.UseOAuthBearerTokens(OAuthOptions);
  
              var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
              {
                  AppId = ConfigurationManager.AppSettings["Test_Facebook_AppId"],
                  AppSecret = ConfigurationManager.AppSettings["Test_Facebook_AppSecret"],
                  //SendAppSecretProof = true,
                  Provider = new FacebookAuthenticationProvider
                  {
                      OnAuthenticated = (context) =&gt;
                      {
                          context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                          return Task.FromResult(0);
                      }
                  }
              };
  
              facebookAuthenticationOptions.Scope.Add("email user_about_me user_location");
              app.UseFacebookAuthentication(facebookAuthenticationOptions);
  
          }
  </code></pre>
  
  <p>The MVC 5 Client (different Project) uses the Web API app for authorization and data. Below is the code to retrieve the Bearer token in case of Username/Password store:</p>
  
  <pre><code>[HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task&lt;ActionResult&gt; Login(LoginViewModel model, string returnUrl)
      {
          if (!ModelState.IsValid)
          {
              model.ExternalProviders = await GetExternalLogins(returnUrl);
              return View(model);
          }
  
          var client = Client.GetClient();
  
          var response = await client.PostAsync("Token", 
              new StringContent(string.Format("grant_type=password&amp;username={0}&amp;password={1}", model.Email, model.Password), Encoding.UTF8));
  
          if (response.IsSuccessStatusCode)
          {
              return RedirectToLocal(returnUrl);
          }
          return View();
      }
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>I could retrieve the Bearer token and then add it to the Authorization Header for subsequent calls. I think that would be ok in case of an Angular App or a SPA. But I think there should be something in MVC that handles it for me, like automatically store it in a cookie and send the cookie on subsequent requests. I have searched around quite a lot and there are posts which hint towards this (<a href="https://stackoverflow.com/questions/21167648/registering-web-api-2-external-logins-from-multiple-api-clients-with-owin-identi">Registering Web API 2 external logins from multiple API clients with OWIN Identity</a>) but I haven't been able to figure out what to do after I get a token.</p>
  
  <p>Do I need to add something in the MVC app Startup.Auth?</p>
  
  <p>Ideally, I need the functionality which the AccountController in ASP.Net Template (MVC + Web API) gives out of box (Logins, Register, External logins, forget password etc etc...) but with the MVC and Web API in different projects.</p>
  
  <p>Is there a template or a git repo which has this boiler plate code?  </p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>Update</strong>
  Incorporating @FrancisDucharme suggestions, below is the code for GrantResourceOwnerCredentials().</p>
  
  <pre><code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
              var userManager = context.OwinContext.GetUserManager&lt;ApplicationUserManager&gt;();
  
              ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
  
              if (user == null)
              {
                  context.SetError("invalid_grant", "The user name or password is incorrect.");
                  return;
              }
  
              ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                 OAuthDefaults.AuthenticationType);
              ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                  CookieAuthenticationDefaults.AuthenticationType);
  
              AuthenticationProperties properties = CreateProperties(user.UserName);
              AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
  
              //Add a response cookie...
              context.Response.Cookies.Append("Token", context.Options.AccessTokenFormat.Protect(ticket));
  
  
              context.Validated(ticket);
              context.Request.Context.Authentication.SignIn(cookiesIdentity);
          }
  </code></pre>
  
  <p>But I can't still seem to get that Cookie or figure out what to do next.</p>
  
  <p><strong>Restating Questions:</strong></p>
  
  <ol>
  <li>What would be the correct way to authenticate, authorize and call Web API methods (Auth and Resource server) from an MVC client?</li>
  <li>Is there boilerplate code or template for AccountController which does the basic plumbing (Login, register - internal/external, forgot password etc.)? </li>
  </ol>