Click here to Skip to main content
16,018,158 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?


What I have tried:

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<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

[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;

  /// <summary>
  /// The startup.
  /// </summary>
  public class Startup
  {
    /// <summary>
    /// The configuration.
    /// </summary>
    /// <param name="app">
    /// The app.
    /// </param>
    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;
    }

    /// <summary>
    /// Setup authorization server
    /// </summary>
    /// <param name="app">
    /// The app.
    /// </param>
    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());
    }
  }
}


<pre>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;

  /// <summary>
  /// The authorization server provider.
  /// </summary>
  public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
  {
    /// <summary>
    /// The validate client authentication.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <returns>
    /// The <see cref="Task"/>.
    /// </returns>
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
      context.Validated();
    }

    /// <summary>
    /// The grant resource owner credentials.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <returns>
    /// The <see cref="Task"/>.
    /// </returns>
    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 { }));
    }
  }
}


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;

  /// <summary>
  /// The msi rest server.
  /// </summary>
  public static class MsiRestServer
  {
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    private static Thread msiWebServer;

    private static bool endServer = false;

    /// <summary>
    /// Gets or sets a value indicating whether use https.
    /// </summary>
    public static bool UseHttps { get; set; }

    /// <summary>
    /// Gets or sets the base address.
    /// </summary>
    public static string BaseAddress { get; set; } = "https://test2234:8443";

    /// <summary>
    /// The startup server.
    /// </summary>
    public static void StartupServer()
    {
      Thread.Sleep(200);
      endServer = false;
      msiWebServer = new Thread(ServerThread);
      msiWebServer.Start();
    }

    /// <summary>
    /// The stop server.
    /// </summary>
    public static void StopServer()
    {
      endServer = true;
    }

    /// <summary>
    /// The server thread.
    /// </summary>
    private static void ServerThread()
    {
      try
      {
        Uri tstAddress = new Uri(BaseAddress);
        //WebServiceHost svcHost = new WebServiceHost();
        // Start OWIN host 
        using (WebApp.Start<Startup>(url: BaseAddress))
        {
          while (!endServer)
          {
            Thread.Sleep(250);
          }
        }
      }
      catch (Exception ex)
      {
        logger.Error(ex);
        MessageBox.Show(ex.Message);
      }
    }
  }
}
Posted
Updated 12-May-20 1:06am
Comments
David_Wimbley 1-Feb-18 11:10am    
I may be missing something but if you want to run it as HTTPS why not just get an SSL cert, put it into IIS and then you have SSL/HTTPS.

1 solution

Hi, I have a doubt regarding your code. Actually, I am also setting up a self hosting owin console app. I wanted to understand how startupserver and stopserver are being called in your code base??


Answer for SSL configuration is to create a certificate and add it in trusted store and run the netsh commands to reserve url and acl and then add sslcert binding
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900