title: Creating Owin Auth Provider that Exchanges a Custom Token for a .Net Auth Cookie
body: <p>I am trying to create an SSO like solution between 2 .Net applications 
  .Net app 1 has a custom token generator and endpoints to validate tokens that returns user information.</p>
  
  <p>.Net application 2 is protected using Owin and was a typical standalone app and a user would directly login using a password and username.</p>
  
  <p>I created (based on <a href="https://coding.abel.nu/2014/06/writing-an-owin-authentication-middleware/" rel="nofollow">Passion for Coding Blog</a> and <a href="https://github.com/AndersAbel/DummyOwinAuth" rel="nofollow">Github</a>) a custom Owin provider that would look for a token either in a Authorization header or as a query parameter from a link that a user would click a link from .Net App 1 and send to the .Net App 2 the token in the query string as at GET (I know this is not secure we are eventually going to use OpenID for what it’s worth we just need this for a demo).  I am able to get the token validate it and create an Identity and authenticate I just cant get the provider to create a .Net Auth Cookie so that subsequent requests are authenticated and not given a 401 error.</p>
  
  <p>Handler File:</p>
  
  <pre><code>using Microsoft.Owin.Infrastructure;
  using Microsoft.Owin.Logging;
  using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.Infrastructure;
  using Newtonsoft.Json;
  using Newtonsoft.Json.Linq;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Security.Claims;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace SomeOAuth
  {
  // Created by the factory in the someAuthenticationMiddleware class.
  class SomeAuthenticationHandler : AuthenticationHandler&lt;SomeAuthenticationOptions&gt;
  {
      private const string HandledResponse = "HandledResponse";
  
      private readonly ILogger _logger;
      private readonly string _challenge;
  
      /// &lt;summary&gt;
      /// Creates a new OpenIdConnectAuthenticationHandler
      /// &lt;/summary&gt;
      /// &lt;param name="logger"&gt;&lt;/param&gt;
      public SomeAuthenticationHandler(ILogger logger, string challenge)
      {
          _logger = logger;
          _challenge = challenge;
      }
  
  
      protected override async Task&lt;AuthenticationTicket&gt; AuthenticateCoreAsync()
      {
          // ASP.Net Identity requires the NameIdentitifer field to be set or it won't  
          // accept the external login (AuthenticationManagerExtensions.GetExternalLoginInfo)
          string requestToken = null;
          string authorization = Request.Headers.Get("Authorization");
  
          if (!string.IsNullOrEmpty(authorization))
          {
              if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
              {
                  requestToken = authorization.Substring("Bearer ".Length).Trim();
              }
          }
  
          if (string.IsNullOrEmpty(requestToken))
          {
              string accessTokenParam = Request.Query.Get("access_token");
              if (!string.IsNullOrEmpty(accessTokenParam))
              {
                  requestToken = accessTokenParam;
              }
          }
  
          if (!string.IsNullOrEmpty(requestToken))
          {
              using (var client = new HttpClient())
              {
                  try
                  {
                      var request = new HttpRequestMessage(HttpMethod.Post, "https://testserver/API/Auth/Authenticate");
                      var s = new StringContent("{\"oauthtoken\":\"" + requestToken + "\"}", Encoding.UTF8, "application/json");
                      // var ts = s.ToString();
                      request.Content = new StringContent("{\"oauthtoken\":\"" + requestToken + "\"}", Encoding.UTF8, "application/json");
  
                      System.Diagnostics.Debug.WriteLine("Request:");
                      System.Diagnostics.Debug.WriteLine(request.ToString());
                      if (request.Content != null)
                      {
                          System.Diagnostics.Debug.WriteLine(await request.Content.ReadAsStringAsync());
                      }
                      System.Diagnostics.Debug.WriteLine("");
  
                      var response = await client.SendAsync(request);
                      if (response.StatusCode != HttpStatusCode.OK)
                      {
                          return null;
                      }
  
                      var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
                      var userId = payload.Value&lt;string&gt;("username");
  
                      //need to get the useid of the user as well as the name and role
  
                      var identity = new ClaimsIdentity("Some");
                      identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "fakeuser", null, "Some"));
                      /*
                      identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName));
                      identity.AddClaim(new Claim(ClaimTypes.Email, user.ContactInfo.Email));
                      identity.AddClaim(new Claim(ClaimTypes.Sid, user.Guid.ToString()));
                      */
                      identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Some"));
                      AuthenticationProperties properties = CreateProperties("fakeusername", "");
                      var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                      return ticket;
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine("asdf e = " + e.Message);
                  }
                  return null;
              }
          }
          else
          {
              return null;
          }
      }
  
      /// &lt;summary&gt;
      /// Handles SignIn
      /// &lt;/summary&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      protected override Task ApplyResponseChallengeAsync()
      {
  
          if (Response.StatusCode == 401)
          {
              AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
              if (challenge == null)
              {
                  return null;
              }
          }
  
          return Task.FromResult&lt;object&gt;(null);
      }
  
  
  
  
      public override Task&lt;bool&gt; InvokeAsync()
      {
          return InvokeReplyPathAsync();
      }
  
      private async Task&lt;bool&gt; InvokeReplyPathAsync()
      {
          AuthenticationTicket ticket = await AuthenticateAsync();
  
          if (ticket != null)
          {
              string value;
              if (ticket.Properties.Dictionary.TryGetValue(HandledResponse, out value) &amp;&amp; value == "true")
              {
                  return true;
              }
              if (ticket.Identity != null)
              {
                  Request.Context.Authentication.SignIn(ticket.Properties, ticket.Identity);
              }
              // Redirect back to the original secured resource, if any.
              if (!string.IsNullOrWhiteSpace(ticket.Properties.RedirectUri))
              {
                  Response.Redirect(ticket.Properties.RedirectUri);
                  return true;
              }
          }
  
          return false;
      }
  
      private static AuthenticationTicket GetHandledResponseTicket()
      {
          return new AuthenticationTicket(null, new AuthenticationProperties(new Dictionary&lt;string, string&gt;() { { HandledResponse, "true" } }));
      }
  
      public AuthenticationProperties CreateProperties(string userName, string Roles)
      {
          IDictionary&lt;string, string&gt; data = new Dictionary&lt;string, string&gt;
      {
          { "userName", userName },
          {"roles",Roles}
      };
          return new AuthenticationProperties(data);
      }
  
    }
  }
  </code></pre>
  
  <p>Middleware file:</p>
  
  <pre><code>using Microsoft.Owin;
  using Microsoft.Owin.Security.Infrastructure;
  using Owin;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.DataProtection;
  using Microsoft.Owin.Security.DataHandler;
  using Microsoft.Owin.Logging;
  
  namespace SomeOAuth
  {
      // One instance is created when the application starts.
      public class SomeeAuthenticationMiddleware : AuthenticationMiddleware&lt;SomeAuthenticationOptions&gt;
      {
          private readonly ILogger _logger;
          private readonly string _challenge = "Bearer";
  
          public SomeAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, SomeAuthenticationOptions options)
              : base(next, options)
          {
  
              _logger = app.CreateLogger&lt;SomeAuthenticationMiddleware&gt;();
  
  
          }
  
          // Called for each request, to create a handler for each request.
          protected override AuthenticationHandler&lt;SomeAuthenticationOptions&gt; CreateHandler()
          {
              return new SomeAuthenticationHandler(_logger, _challenge);
          }
      }
  }
  </code></pre>
  
  <p>Options file:</p>
  
  <pre><code>using Microsoft.Owin;
  using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.OAuth;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace SomeOAuth
  {
      public class SomeAuthenticationOptions : AuthenticationOptions
      {
          public SomeAuthenticationOptions(string userName, string userId)
              : base(OAuthDefaults.AuthenticationType)
          {
              UserName = userName;
              UserId = userId;
          }
  
          public string Challenge { get; set; }
  
          public string UserName { get; set; }
  
          public string UserId { get; set; }
  
      }
  }
  </code></pre>
  
  <p>Extensions File:</p>
  
  <pre><code>using Microsoft.Owin.Extensions;
  using Owin;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace SomeOAuth
  {
  
      public static class SomeAuthenticationExtensions
      {
          public static IAppBuilder UseSomeeAuthentication(this IAppBuilder app, SomeAuthenticationOptions options)
          {
              if (app == null)
              {
                  throw new ArgumentNullException("app");
              }
  
              app.Use(typeof(SomeAuthenticationMiddleware), app, options);
              app.UseStageMarker(PipelineStage.Authenticate);
  
              return app;
          }
      }
  }
  </code></pre>
  
  <p>Startup File</p>
  
  <pre><code>using System;
  using CoreLX.Palms.VS.Web.Services;
  using Microsoft.AspNet.Identity;
  using Microsoft.AspNet.Identity.Owin;
  using Microsoft.Owin;
  using Microsoft.Owin.Security.Cookies;
  using Owin.Security.Providers.OpenID;
  using Microsoft.Owin.Security.OAuth;
  using Owin;
  using SomeOAuth;
  using CoreLX.Palms.LS.Web.Common.Models.User;
  
  namespace CoreLX.Palms.VS.Web
  {
      public partial class Startup
      {
  
          public void ConfigureAuth(IAppBuilder app)
          {
  
              app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
          app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;    (ApplicationSignInManager.Create);
  
              //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
              //{
              //    AccessTokenProvider = new SomeTokenProvider(),
              //    Provider = new SomeOAuthBearerAuthenticationProvider("access_token")
              //});
  
              app.UseSomeAuthentication(new SomeAuthenticationOptions("testuser", "9"));
  
              // Use a cookie to temp store information about a user     logging in with a third party login provider
              app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  
              // Enable the application to use a cookie to store information for the signed in user
              app.UseCookieAuthentication(
                  new CookieAuthenticationOptions
                  {
                      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                      LoginPath = new PathString("/Account/Login"),
                      ExpireTimeSpan = new TimeSpan(0, 3, 0, 0),
                      Provider = new CookieAuthenticationProvider
                      {
                          OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;(
                          validateInterval: TimeSpan.FromMinutes(30),
                          regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager)),
                          OnApplyRedirect = ctx =&gt;
                                  {
                                  // don't redirect to login page for webapi/ajax requests
                                  // http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
                                  if (!IsWebApiRequest(ctx.Request))
                                  {
                                      ctx.Response.Redirect(ctx.RedirectUri);
                                  }
                              }
                      }
                  });
  
  
  
              app.UseOpenIDAuthentication("http://me.yahoo.com/", "Yahoo");
  
  
  
          }
  
  
          private static bool IsWebApiRequest(IOwinRequest request)
          {
              // hack for check if it's webapi requesr
              if (request.Path.StartsWithSegments(new PathString("/api")))
              {
              return true;
              }
  
              // checks if it's ajax request
              IReadableStringCollection query = request.Query;
              if ((query != null) &amp;&amp; (query["X-Requested-With"] == "XMLHttpRequest"))
              {
                  return true;
              }
              IHeaderDictionary headers = request.Headers;
              return ((headers != null) &amp;&amp; (headers["X-Requested-With"] ==     "XMLHttpRequest"));
      }
      }
  }
  </code></pre>
  
  <p>I have also tried to just use the custom providers for the standard provided</p>
  
  <pre><code>OAuthBearerAuthenticationProvider
  </code></pre>
  
  <p>Here is the code for the plugins/providers that I tried I don't have a preference as long as there are no 401 errors:</p>
  
  <p>Provider</p>
  
  <pre><code>using Microsoft.Owin.Security.OAuth;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace SomeOAuth
  {
      public class SomeOAuthBearerAuthenticationProvider : IOAuthBearerAuthenticationProvider
      {
          readonly string _parameterName;
          public SomeOAuthBearerAuthenticationProvider(string parameterName)
          {
              _parameterName = parameterName;
          }
          public Task ApplyChallenge(OAuthChallengeContext context)
          {
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public Task RequestToken(OAuthRequestTokenContext context)
          {
              string token = context.Token;
              if(string.IsNullOrEmpty(token) &amp;&amp;     !string.IsNullOrEmpty(_parameterName))
              {
                  token = context.Request.Query.Get(_parameterName);
              }
  
              if (!string.IsNullOrEmpty(token))
              {
                  context.Token = token;
              }
  
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public Task ValidateIdentity(OAuthValidateIdentityContext context)
          {
              context.Validated();
              return Task.FromResult&lt;object&gt;(null);
          }
      }
  }
  </code></pre>
  
  <p>And the AccessTokenProvider</p>
  
  <pre><code>using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.Infrastructure;
  using Newtonsoft.Json.Linq;
  using System;
  //using Newtonsoft.Json.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Security.Claims;
  using System.Text;
  using System.Threading.Tasks;
  
  
  namespace SomeOAuth
  {
      public sealed class SomeTokenProvider : AuthenticationTokenProvider
      {
          public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
          {
              using (var client = new HttpClient())
              {
                  try
                  {
                      var request = new HttpRequestMessage(HttpMethod.Post, "https://someserver/API/Auth/Authenticate");
                      var s = new StringContent("{\"oauthtoken\":\"" + context.Token + "\"}", Encoding.UTF8, "application/json");
                      // var ts = s.ToString();
                      request.Content = new StringContent("{\"oauthtoken\":\"" + context.Token + "\"}", Encoding.UTF8, "application/json");
  
                      System.Diagnostics.Debug.WriteLine("Request:");
                      System.Diagnostics.Debug.WriteLine(request.ToString());
                      if (request.Content != null)
                      {
                          System.Diagnostics.Debug.WriteLine(await request.Content.ReadAsStringAsync());
                      }
                      System.Diagnostics.Debug.WriteLine("");
  
                      var response = await client.SendAsync(request);
                      if (response.StatusCode != HttpStatusCode.OK)
                      {
                          return;
                      }
  
                      var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
                      var userId = payload.Value&lt;string&gt;("username");
  
                      //need to get the useid of the user as well as the name and role
  
                      var identity = new ClaimsIdentity("Some");
                      identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "someuser", null, "Some"));
                  /*
                      identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName));
                      identity.AddClaim(new Claim(ClaimTypes.Email, user.ContactInfo.Email));
                      identity.AddClaim(new Claim(ClaimTypes.Sid, user.Guid.ToString()));
                      */
                      identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Some"));
                      context.SetTicket(new AuthenticationTicket(identity, new AuthenticationProperties()));
                  }
                  catch (Exception e)
                  {
                      Console.WriteLine("asdf e = " + e.Message);
                  }
              }
          }
      }
  }
  </code></pre>