title: How to send bearer token to views in ASP NET MVC 5?
body: <p>I have a <code>.NET MVC</code> and <code>WEB API</code> project. I want to call the <code>WEB API controllers</code> from javascript but I didn't find a way to send the token to my views. I want to add the <code>bearer token</code> in <code>Viewbag</code> variable, using the below code:</p>
  
  <pre><code>protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      //GetBearerToken doesn't exists
      ViewBag.BearerToken = Request.GetOwinContext().GetBearerToken();
  }
  </code></pre>
  
  <p>In <code>_Layout.cshtml</code>, I added the folowing code to set <code>Authorization</code> header for all ajax requests:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      window.token = '@Viewbag.BearerToken';
  
      // Add Authorization header on ajax requests
      if(window.token) {
          (function setAjaxRequestsAuthorizationHeader(token) {
              $.ajaxPrefilter(function onAjaxPrefilter(options) {
                  if (!options.beforeSend) {
                      options.beforeSend = function onBeforeSend(xhr) {
                          xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                      }
                  }
              });
          }(window.token));
          window.token = null;
      }
  
  &lt;/script&gt;
  </code></pre>
  
  <p>Below is my Startup configuration method:</p>
  
  <pre><code>public void ConfigureAuth(IAppBuilder app)
  {
  
      // Configure the db context, user manager and signin manager to use a single instance per request
      //app.CreatePerOwinContext(ApplicationDbContext.Create);
      app.CreatePerOwinContext(AppDbContext.Create);
      app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
      app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(ApplicationSignInManager.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
      // Configure the sign in cookie
      app.UseCookieAuthentication(new CookieAuthenticationOptions
      {
          AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
          LoginPath = new PathString("/Account/Login"),
          Provider = new CookieAuthenticationProvider
          {
              // Enables the application to validate the security stamp when the user logs in.
              // This is a security feature which is used when you change a password or add an external login to your account.  
              OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, User, int&gt;(
                  validateInterval: TimeSpan.FromMinutes(30),
                  regenerateIdentityCallback: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager),
                  getUserIdCallback: id =&gt; id.GetUserId&lt;int&gt;())
          }
      });
      app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  
      PublicClientId = "self";
      OAuthOptions = new OAuthAuthorizationServerOptions
      {
          TokenEndpointPath = new PathString("/Token"),
          Provider = new ApplicationOAuthProvider(PublicClientId),
          AuthorizeEndpointPath = new PathString("/api/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);
  
      // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
      app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
      app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
  
  }
  </code></pre>
  
  <p>To get a <code>token</code> I also tried (in the MVC Controller methods):</p>
  
  <pre><code>var token = new ClaimsPrincipal(User.Identity).Claims.FirstOrDefault(x =&gt; x.Type == "access_token")?.Value;
  </code></pre>
  
  <p>But the value of variable token is always null.</p>
  
  <p>I have also inspected all claims values but I didn't find any possible token.  </p>
  
  <p>How can I send the <code>token</code> to <code>controller views</code>?</p>
  
  <p><strong>Solved</strong></p>
  
  <p>I solved the problem by doing the following steps:</p>
  
  <ol>
  <li><p>In <code>Startup.Auth.cs</code> I added the folowing static property:</p>
  
  <pre><code> public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
  </code></pre></li>
  <li><p>I have created an extension method for <code>ApplicationUser</code> class:</p>
  
  <pre><code>public static async Task&lt;ClaimsIdentity&gt; GenerateUserIdentityAsync(this ApplicationUser user, UserManager&lt;ApplicationUser, int&gt; manager, string type)
  {
      // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
      var userIdentity = await manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
      // Genereate Bearer token
      if (manager is ApplicationUserManager &amp;&amp; type == DefaultAuthenticationTypes.ApplicationCookie)
      {
          var accessTokenFormat = Startup.OAuthOptions.AccessTokenFormat;
          if (accessTokenFormat != null)
          {
              IDictionary&lt;string, string&gt; data = new Dictionary&lt;string, string&gt;
              {
                  ["userName"] = user.UserName
              };
  
              AuthenticationProperties properties = new AuthenticationProperties(data);
              AuthenticationTicket ticket = new AuthenticationTicket(userIdentity, properties);
  
              var token = accessTokenFormat.Protect(ticket);
              userIdentity.AddClaim(new Claim("Access_Token", token));
          }
      }
      return userIdentity;
  }
  </code></pre></li>
  <li><p>I modified the method <code>OnActionExecuting</code> to send token to the client:</p>
  
  <pre><code>protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      if (Request.IsAuthenticated)
      {
          var identity = (ClaimsIdentity)User.Identity;
          ViewBag.BearerToken = identity.Claims.FirstOrDefault(x =&gt; x.Type == "Access_Token")?.Value;
      }
  }
  </code></pre></li>
  <li><p>In <code>Startup.Auth.cs</code> use the extension method created at step 2 when creating <code>Identity</code>:</p>
  
  <pre><code>OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser, int&gt;(
      validateInterval: TimeSpan.FromMinutes(30),
      regenerateIdentityCallback: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager,
      DefaultAuthenticationTypes.ApplicationCookie),
      getUserIdCallback: id =&gt; id.GetUserId&lt;int&gt;())
  </code></pre></li>
  </ol>