调整api为hostingstarup

This commit is contained in:
Gui.H 2022-07-01 11:45:27 +08:00
parent 04c956a030
commit f7091e6fd5
8 changed files with 186 additions and 142 deletions

View File

@ -13,8 +13,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FastTunnel.Api.Controllers
{
namespace FastTunnel.Api.Controllers;
public class SystemController : BaseController
{
readonly FastTunnelServer fastTunnelServer;
@ -24,18 +24,6 @@ namespace FastTunnel.Api.Controllers
this.fastTunnelServer = fastTunnelServer;
}
/// <summary>
/// 获取当前等待响应的请求数
/// </summary>
/// <returns></returns>
[HttpGet]
[Obsolete("使用 GetResponseTempList 替换")]
public ApiResponse GetResponseTempCount()
{
ApiResponse.data = fastTunnelServer.ResponseTasks.Count;
return ApiResponse;
}
/// <summary>
/// 获取当前等待响应的请求
/// </summary>
@ -110,4 +98,3 @@ namespace FastTunnel.Api.Controllers
return ApiResponse;
}
}
}

View File

@ -9,8 +9,9 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.4" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.10.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.10.0" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,80 @@
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE
// Copyright (c) 2019 Gui.H
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FastTunnel.Api;
using FastTunnel.Api.Filters;
using FastTunnel.Core.Config;
using FastTunnel.Core.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
[assembly: HostingStartup(typeof(FastTunnelApiHostingStartup))]
namespace FastTunnel.Api;
public class FastTunnelApiHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
Debug.WriteLine("FastTunnelApiHostingStartup Configured");
builder.ConfigureServices((webHostBuilderContext, services) =>
{
services.AddControllers();
var serverOptions = webHostBuilderContext.Configuration.GetSection("FastTunnel").Get<DefaultServerConfig>();
if (serverOptions.Api?.JWT != null)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(serverOptions.Api.JWT.ClockSkew),
ValidateIssuerSigningKey = true,
ValidAudience = serverOptions.Api.JWT.ValidAudience,
ValidIssuer = serverOptions.Api.JWT.ValidIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverOptions.Api.JWT.IssuerSigningKey))
};
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
context.HandleResponse();
context.Response.ContentType = "application/json;charset=utf-8";
context.Response.StatusCode = StatusCodes.Status200OK;
await context.Response.WriteAsync(new
{
errorCode = 1,
errorMessage = context.Error ?? "Token is Required"
}.ToJson());
},
};
});
}
services.AddSingleton<CustomExceptionFilterAttribute>();
});
}
}

View File

@ -18,10 +18,6 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>FastTunnel.Core</PackageReleaseNotes>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="5.0.0" />

View File

@ -12,6 +12,7 @@ using FastTunnel.Core.Models;
using FastTunnel.Core.Models.Massage;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
@ -36,6 +37,8 @@ namespace FastTunnel.Core.Handlers.Server
{
bool hasTunnel = false;
List<string> tips = new List<string>();
await client.webSocket.SendCmdAsync(MessageType.Log, $"穿透协议 | 映射关系(公网=>内网)", CancellationToken.None);
Thread.Sleep(300);
@ -80,6 +83,12 @@ namespace FastTunnel.Core.Handlers.Server
{
try
{
if (item.LocalPort == 3389)
tips.Add("您已将3389端口暴露请确保您的PC密码足够安全。");
if (item.LocalPort == 22)
tips.Add("您已将22端口暴露请确保您的PC密码足够安全。");
ForwardInfo<ForwardHandlerArg> old;
if (server.ForwardList.TryGetValue(item.RemotePort, out old))
{
@ -116,6 +125,11 @@ namespace FastTunnel.Core.Handlers.Server
}
}
foreach (var item in tips)
{
await client.webSocket.SendCmdAsync(MessageType.Log, item, CancellationToken.None);
}
if (!hasTunnel)
await client.webSocket.SendCmdAsync(MessageType.Log, TunnelResource.NoTunnel, CancellationToken.None);
}

View File

@ -33,6 +33,9 @@ public class Program
.UseWindowsService()
.ConfigureWebHost(webHostBuilder =>
{
// Use FastTunnelHostingStartup
webHostBuilder.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "FastTunnel.Api");
webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;

View File

@ -14,7 +14,8 @@
"launchBrowser": true,
"launchUrl": "http://localhost:1270/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"ASPNETCORE_ENVIRONMENT": "Development",
//"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "FastTunnel.Api;FastTunnel.Core"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
},

View File

@ -36,41 +36,6 @@ public class Startup
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var serverOptions = Configuration.GetSection("FastTunnel").Get<DefaultServerConfig>();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(serverOptions.Api.JWT.ClockSkew),
ValidateIssuerSigningKey = true,
ValidAudience = serverOptions.Api.JWT.ValidAudience,
ValidIssuer = serverOptions.Api.JWT.ValidIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverOptions.Api.JWT.IssuerSigningKey))
};
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
context.HandleResponse();
context.Response.ContentType = "application/json;charset=utf-8";
context.Response.StatusCode = StatusCodes.Status200OK;
await context.Response.WriteAsync(new
{
errorCode = 1,
errorMessage = context.Error ?? "Token is Required"
}.ToJson());
},
};
});
services.AddAuthorization();
services.AddControllers();
@ -81,7 +46,6 @@ public class Startup
c.SwaggerDoc("v2", new OpenApiInfo { Title = "FastTunel.Api", Version = "v2" });
});
#endif
services.AddSingleton<CustomExceptionFilterAttribute>();
// -------------------FastTunnel STEP1 OF 3------------------
services.AddFastTunnelServer(Configuration.GetSection("FastTunnel"));
// -------------------FastTunnel STEP1 END-------------------
@ -105,11 +69,9 @@ public class Startup
app.UseFastTunnelServer();
// -------------------FastTunnel STEP2 END-------------------
// --------------------- Custom UI ----------------
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
// --------------------- Custom UI ----------------
app.UseEndpoints(endpoints =>
{