title: Owin OAuth HTTPS Rest webservice
body: <p>I would like to implement a HTTPS connection for my rest webservice.
  The HTTP version works as well, but when i try to connect over HTTPS and send a XML file or something else, It already fails when establishing the connection via https.
  Has someone an idea what i can change to test it over https?</p>
  
  <p>Startup.cs:</p>
  
  <pre><code>using System;
  using Owin;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  using System.Web.Http;
  using Microsoft.Owin;
  using Microsoft.Owin.Security.OAuth;
  using AppFunc = System.Func&lt;System.Collections.Generic.IDictionary&lt;string, object&gt;, System.Threading.Tasks.Task&gt;;
  
  [assembly: OwinStartup(typeof(SimuXmlDcs.MsiWebServer.Startup))]
  
  namespace SimuXmlDcs.MsiWebServer
  {
    using System.Configuration;
    using System.Net;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Cryptography.X509Certificates;
    using System.Web.Http;
    using Microsoft.Owin.Security;
    using Newtonsoft.Json;
  
    using SimuXmlDcs.MsiWebServer.App_Start;
    using SimuXmlDcs.MsiWebServer.Controllers;
  
    /// &lt;summary&gt;
    /// The startup.
    /// &lt;/summary&gt;
    public class Startup
    {
      /// &lt;summary&gt;
      /// The configuration.
      /// &lt;/summary&gt;
      /// &lt;param name="app"&gt;
      /// The app.
      /// &lt;/param&gt;
      public void Configuration(IAppBuilder app)
      {
        ConfigureOAuth(app);
  
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
  
        config.MapHttpAttributeRoutes();
  
        config.Routes.MapHttpRoute(name: "SystemAction", routeTemplate: "api/{controller}/{system}/{action}", defaults: new { action = RouteParameter.Optional });
  
        config.Routes.MapHttpRoute(name: "System", routeTemplate: "api/{controller}/{system}");      
  
        config.Routes.MapHttpRoute(name: "Info", routeTemplate: "api/{controller}");
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        config.Formatters.XmlFormatter.UseXmlSerializer = true;
        app.UseWebApi(config);
  
        //byte[] test = new byte[4];
        //test[0] = 10;
        //test[1] = 78;
        //test[2] = 2;
        //test[3] = 193;
        //IPAddress ipaddress = new IPAddress(test);
  
        //TcpListener server = new TcpListener(ipaddress, 8443);
        //server.Start();
  
        //TcpClient client = server.AcceptTcpClient();
        //SslStream stream = new SslStream(client.GetStream(), false, VerifyClientCertificate, null);
      }
  
      private static bool VerifyClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
      {
        return true;
      }
  
      /// &lt;summary&gt;
      /// Setup authorization server
      /// &lt;/summary&gt;
      /// &lt;param name="app"&gt;
      /// The app.
      /// &lt;/param&gt;
      private void ConfigureOAuth(IAppBuilder app)
      {
        int timeSpan;
        AppSettingsReader asr = new AppSettingsReader();
        int.TryParse(asr.GetValue("TokenExpireInMinutes", typeof(string)).ToString(), out timeSpan);
  
        app.UseOAuthAuthorizationServer(
          new OAuthAuthorizationServerOptions()
            {
              AllowInsecureHttp = !MsiRestServer.UseHttps,
              TokenEndpointPath = new PathString("/api/getsecuretoken"),
              AccessTokenExpireTimeSpan = timeSpan != 0 ? TimeSpan.FromMinutes(timeSpan) : TimeSpan.FromDays(1),
              Provider = new AuthorizationServerProvider(),
              ApplicationCanDisplayErrors = true
            });
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
      }
    }
  }
  </code></pre>
  
  <p>AuthorizationServerProvider</p>
  
  <pre><code>namespace SimuXmlDcs.MsiWebServer.App_Start
  {
    using System.Security.Claims;
    using System.Threading.Tasks;
  
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.OAuth;
  
    using SimuXmlDcs.MsiWebServer.Models;
  
    /// &lt;summary&gt;
    /// The authorization server provider.
    /// &lt;/summary&gt;
    public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
      /// &lt;summary&gt;
      /// The validate client authentication.
      /// &lt;/summary&gt;
      /// &lt;param name="context"&gt;
      /// The context.
      /// &lt;/param&gt;
      /// &lt;returns&gt;
      /// The &lt;see cref="Task"/&gt;.
      /// &lt;/returns&gt;
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
      {
        context.Validated();
      }
  
      /// &lt;summary&gt;
      /// The grant resource owner credentials.
      /// &lt;/summary&gt;
      /// &lt;param name="context"&gt;
      /// The context.
      /// &lt;/param&gt;
      /// &lt;returns&gt;
      /// The &lt;see cref="Task"/&gt;.
      /// &lt;/returns&gt;
      public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
      {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
  
        if (context.Password != "password")
        {
          context.SetError("invalid_grant", "The user name or password is incorrect.");
          return;
        }
  
        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Role, RoleName.Admin));
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
  
        context.Validated(new AuthenticationTicket(identity, new AuthenticationProperties { }));
      }
    }
  }
  </code></pre>
  
  <p>MsiRestServer</p>
  
  <pre><code>namespace SimuXmlDcs.MsiWebServer
  {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows;
  
    using log4net;
  
    using Microsoft.Owin.Hosting;
  
    /// &lt;summary&gt;
    /// The msi rest server.
    /// &lt;/summary&gt;
    public static class MsiRestServer
    {
      private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  
      private static Thread msiWebServer;
  
      private static bool endServer = false;
  
      /// &lt;summary&gt;
      /// Gets or sets a value indicating whether use https.
      /// &lt;/summary&gt;
      public static bool UseHttps { get; set; }
  
      /// &lt;summary&gt;
      /// Gets or sets the base address.
      /// &lt;/summary&gt;
      public static string BaseAddress { get; set; } = "https://test2234:8443";
  
      /// &lt;summary&gt;
      /// The startup server.
      /// &lt;/summary&gt;
      public static void StartupServer()
      {
        Thread.Sleep(200);
        endServer = false;
        msiWebServer = new Thread(ServerThread);
        msiWebServer.Start();
      }
  
      /// &lt;summary&gt;
      /// The stop server.
      /// &lt;/summary&gt;
      public static void StopServer()
      {
        endServer = true;
      }
  
      /// &lt;summary&gt;
      /// The server thread.
      /// &lt;/summary&gt;
      private static void ServerThread()
      {
        try
        {
          Uri tstAddress = new Uri(BaseAddress);
          //WebServiceHost svcHost = new WebServiceHost();
          // Start OWIN host 
          using (WebApp.Start&lt;Startup&gt;(url: BaseAddress))
          {
            while (!endServer)
            {
              Thread.Sleep(250);
            }
          }
        }
        catch (Exception ex)
        {
          logger.Error(ex);
          MessageBox.Show(ex.Message);
        }
      }
    }
  }
  </code></pre>