invidicult Ответов: 1

HTTPS через owin rest webservice


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?


Что я уже пробовал:

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);
      }
    }
  }
}

David_Wimbley

Возможно, я что-то упускаю, но если вы хотите запустить его как HTTPS, почему бы просто не получить сертификат SSL, поместить его в IIS, а затем у вас есть SSL/HTTPS.

1 Ответов

Рейтинг:
2

Member 14829629

Привет, у меня есть сомнения относительно вашего кода. На самом деле, я также настраиваю самостоятельное хостинговое консольное приложение owin. Я хотел понять, как startupserver и stopserver вызываются в вашей кодовой базе??


Ответ для конфигурации SSL состоит в том, чтобы создать сертификат и добавить его в доверенное хранилище, а также выполнить команды netsh для резервирования url и acl, а затем добавить привязку sslcert