调整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,101 +13,88 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace FastTunnel.Api.Controllers namespace FastTunnel.Api.Controllers;
public class SystemController : BaseController
{ {
public class SystemController : BaseController readonly FastTunnelServer fastTunnelServer;
public SystemController(FastTunnelServer fastTunnelServer)
{ {
readonly FastTunnelServer fastTunnelServer; this.fastTunnelServer = fastTunnelServer;
}
public SystemController(FastTunnelServer fastTunnelServer) /// <summary>
/// 获取当前等待响应的请求
/// </summary>
/// <returns></returns>
[HttpGet]
public ApiResponse GetResponseTempList()
{
ApiResponse.data = new
{ {
this.fastTunnelServer = fastTunnelServer; Count = fastTunnelServer.ResponseTasks.Count,
} Rows = fastTunnelServer.ResponseTasks.Select(x => new
/// <summary>
/// 获取当前等待响应的请求数
/// </summary>
/// <returns></returns>
[HttpGet]
[Obsolete("使用 GetResponseTempList 替换")]
public ApiResponse GetResponseTempCount()
{
ApiResponse.data = fastTunnelServer.ResponseTasks.Count;
return ApiResponse;
}
/// <summary>
/// 获取当前等待响应的请求
/// </summary>
/// <returns></returns>
[HttpGet]
public ApiResponse GetResponseTempList()
{
ApiResponse.data = new
{ {
Count = fastTunnelServer.ResponseTasks.Count, x.Key
Rows = fastTunnelServer.ResponseTasks.Select(x => new })
{ };
x.Key
})
};
return ApiResponse; return ApiResponse;
} }
/// <summary> /// <summary>
/// 获取当前映射的所有站点信息 /// 获取当前映射的所有站点信息
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
public ApiResponse GetAllWebList() public ApiResponse GetAllWebList()
{
ApiResponse.data = new
{ {
ApiResponse.data = new Count = fastTunnelServer.WebList.Count,
{ Rows = fastTunnelServer.WebList.Select(x => new { x.Key, x.Value.WebConfig.LocalIp, x.Value.WebConfig.LocalPort })
Count = fastTunnelServer.WebList.Count, };
Rows = fastTunnelServer.WebList.Select(x => new { x.Key, x.Value.WebConfig.LocalIp, x.Value.WebConfig.LocalPort })
};
return ApiResponse; return ApiResponse;
} }
/// <summary> /// <summary>
/// 获取服务端配置信息 /// 获取服务端配置信息
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
public ApiResponse GetServerOption() public ApiResponse GetServerOption()
{
ApiResponse.data = fastTunnelServer.ServerOption;
return ApiResponse;
}
/// <summary>
/// 获取所有端口转发映射列表
/// </summary>
/// <returns></returns>
[HttpGet]
public ApiResponse GetAllForwardList()
{
ApiResponse.data = new
{ {
ApiResponse.data = fastTunnelServer.ServerOption; Count = fastTunnelServer.ForwardList.Count,
return ApiResponse; Rows = fastTunnelServer.ForwardList.Select(x => new { x.Key, x.Value.SSHConfig.LocalIp, x.Value.SSHConfig.LocalPort, x.Value.SSHConfig.RemotePort })
}
/// <summary> };
/// 获取所有端口转发映射列表
/// </summary>
/// <returns></returns>
[HttpGet]
public ApiResponse GetAllForwardList()
{
ApiResponse.data = new
{
Count = fastTunnelServer.ForwardList.Count,
Rows = fastTunnelServer.ForwardList.Select(x => new { x.Key, x.Value.SSHConfig.LocalIp, x.Value.SSHConfig.LocalPort, x.Value.SSHConfig.RemotePort })
}; return ApiResponse;
}
return ApiResponse; /// <summary>
} /// 获取当前客户端在线数量
/// </summary>
/// <summary> /// <returns></returns>
/// 获取当前客户端在线数量 [HttpGet]
/// </summary> public ApiResponse GetOnlineClientCount()
/// <returns></returns> {
[HttpGet] ApiResponse.data = fastTunnelServer.ConnectedClientCount;
public ApiResponse GetOnlineClientCount() return ApiResponse;
{
ApiResponse.data = fastTunnelServer.ConnectedClientCount;
return ApiResponse;
}
} }
} }

View File

@ -1,19 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net6.0</TargetFrameworks> <TargetFrameworks>net6.0</TargetFrameworks>
<Version>1.1.0</Version> <Version>1.1.0</Version>
<PackageProjectUrl>https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api</PackageProjectUrl> <PackageProjectUrl>https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api</PackageProjectUrl>
<RepositoryUrl>https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api</RepositoryUrl> <RepositoryUrl>https://github.com/FastTunnel/FastTunnel/tree/v2/FastTunnel.Api</RepositoryUrl>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.4" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.10.0" />
</ItemGroup> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.10.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FastTunnel.Core\FastTunnel.Core.csproj" /> <ProjectReference Include="..\FastTunnel.Core\FastTunnel.Core.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

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

View File

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

View File

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

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. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) 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.AddAuthorization();
services.AddControllers(); services.AddControllers();
@ -81,7 +46,6 @@ public class Startup
c.SwaggerDoc("v2", new OpenApiInfo { Title = "FastTunel.Api", Version = "v2" }); c.SwaggerDoc("v2", new OpenApiInfo { Title = "FastTunel.Api", Version = "v2" });
}); });
#endif #endif
services.AddSingleton<CustomExceptionFilterAttribute>();
// -------------------FastTunnel STEP1 OF 3------------------ // -------------------FastTunnel STEP1 OF 3------------------
services.AddFastTunnelServer(Configuration.GetSection("FastTunnel")); services.AddFastTunnelServer(Configuration.GetSection("FastTunnel"));
// -------------------FastTunnel STEP1 END------------------- // -------------------FastTunnel STEP1 END-------------------
@ -105,11 +69,9 @@ public class Startup
app.UseFastTunnelServer(); app.UseFastTunnelServer();
// -------------------FastTunnel STEP2 END------------------- // -------------------FastTunnel STEP2 END-------------------
// --------------------- Custom UI ----------------
app.UseStaticFiles(); app.UseStaticFiles();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
// --------------------- Custom UI ----------------
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {