我想为其余的webservice实现HTTPS连接。 HTTP版本也可以,但是当我尝试通过HTTPS连接并发送XML文件或其他内容时,通过https建立连接时它已经失败。 有人知道我可以通过https测试它吗?
Startup.cs:
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());
}
}
}
AuthorizationServerProvider
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 { }));
}
}
}
MsiRestServer
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);
}
}
}
}
答案 0 :(得分:1)
对于自托管应用,您必须创建证书。
http://chavli.com/how-to-configure-owin-self-hosted-website-with-ssl/
但是当您使用IIS时,您只需启用项目属性“SSL enabled”。