title: How to setup MVC requests to use Oauth 2.0 access token?
body: <p>I am working on an Asp.net Web API + MVC project. While creating the project, I selected 'Individual User Accounts' option for authentication. After login, the provider issues access token and I use this token in HTTP header of ajax calls and it works fine with Ajax calls. I also have MVC actions which are used to navigate to different pages. These actions are protected using [Authorize] attribute of System.web.MVC. While navigating to these actions authorization fails and I am redirected to login page. How do I configure Oauth 2.0 access token to be used in non ajax requests (MVC requests) also.</p>
  
  <p><strong>Startup.Auth.cs:</strong></p>
  
  <pre><code>public partial class Startup
      {
          public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
  
          public static string PublicClientId { get; private set; }
  
          // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
          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 { 
                  AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                  LoginPath = new PathString("/Home/Login"),
                  LogoutPath = new PathString("/Account/LogOff"),
                  ExpireTimeSpan = TimeSpan.FromHours(1.0),
              });
              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("/api/Account/ExternalLogin"),
                  AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                  AllowInsecureHttp = true // dont use this for production,
              };
  
              // Enable the application to use bearer tokens to authenticate users
              app.UseOAuthBearerTokens(OAuthOptions);
  
          }
  </code></pre>
  
  <p><strong>WebApiConfig.cs:</strong></p>
  
  <pre><code>public static void Register(HttpConfiguration config)
          {
              // Web API configuration and services
              // Configure Web API to use only bearer token authentication.
              config.SuppressDefaultHostAuthentication();
              config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
  
              // Web API routes
              config.MapHttpAttributeRoutes();
  
              config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
          }
  </code></pre>
  
  <p><strong>ApplicationOAuthProvider.cs:</strong></p>
  
  <pre><code>public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
      {
          private readonly string _publicClientId;
  
          public ApplicationOAuthProvider(string publicClientId)
          {
              if (publicClientId == null)
              {
                  throw new ArgumentNullException("publicClientId");
              }
  
              _publicClientId = publicClientId;
          }
  
          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);
              context.Validated(ticket);
              context.Request.Context.Authentication.SignIn(cookiesIdentity);
          }
  
          public override Task TokenEndpoint(OAuthTokenEndpointContext context)
          {
              foreach (KeyValuePair&lt;string, string&gt; property in context.Properties.Dictionary)
              {
                  context.AdditionalResponseParameters.Add(property.Key, property.Value);
              }
  
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
          {
              // Resource owner password credentials does not provide a client ID.
              if (context.ClientId == null)
              {
                  context.Validated();
              }
  
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
          {
              if (context.ClientId == _publicClientId)
              {
                  Uri expectedRootUri = new Uri(context.Request.Uri, "/");
  
                  if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                  {
                      context.Validated();
                  }
              }
  
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public static AuthenticationProperties CreateProperties(string userName)
          {
              IDictionary&lt;string, string&gt; data = new Dictionary&lt;string, string&gt;
              {
                  { "userName", userName }
              };
              return new AuthenticationProperties(data);
          }
      }
  </code></pre>