Skip to content

Commit

Permalink
feat: 新增 JWT 封装
Browse files Browse the repository at this point in the history
  • Loading branch information
jianxuanbing committed Sep 19, 2019
1 parent d70f3a9 commit dfd8493
Show file tree
Hide file tree
Showing 16 changed files with 613 additions and 40 deletions.
9 changes: 8 additions & 1 deletion Bing.NetCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bing.Datas.EntityFramework.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bing.MiniProfiler", "src\Bing.MiniProfiler\Bing.MiniProfiler.csproj", "{EFC2120A-C3C9-472B-B464-7AF4E5F4846F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bing.Permissions", "src\Bing.Permissions\Bing.Permissions.csproj", "{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bing.Permissions", "src\Bing.Permissions\Bing.Permissions.csproj", "{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bing.Samples.Jwt", "sample\Bing.Samples.Jwt\Bing.Samples.Jwt.csproj", "{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -458,6 +460,10 @@ Global
{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F}.Release|Any CPU.Build.0 = Release|Any CPU
{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -553,6 +559,7 @@ Global
{7D3CE260-BF01-4F48-AB9F-B73BF293FDE4} = {919230E8-CEFA-48BC-958A-42601DB44C4A}
{EFC2120A-C3C9-472B-B464-7AF4E5F4846F} = {FF7DDF01-C939-468A-A1D8-F85624E17856}
{1DA7A52C-D593-4B04-9A5B-1136BDC3D69F} = {54819E6C-8549-42E9-94C4-45EDB37F0C22}
{0A8432D1-A6DA-4FA6-9CDD-5D6F4400C106} = {474AB182-21D2-44C4-A99C-31FC31E469CB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {82408448-62DC-44A6-B7C1-6FCEBCC12C93}
Expand Down
31 changes: 31 additions & 0 deletions sample/Bing.Samples.Jwt/Bing.Samples.Jwt.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Bing.Extensions.Swashbuckle" Version="1.1.0" />
<PackageReference Include="EasyCaching.CSRedis" Version="0.6.1" />
<PackageReference Include="EasyCaching.Redis" Version="0.6.1" />
<PackageReference Include="EasyCaching.Serialization.Json" Version="0.6.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Bing.AspNetCore\Bing.AspNetCore.csproj" />
<ProjectReference Include="..\..\src\Bing.EasyCaching\Bing.EasyCaching.csproj" />
<ProjectReference Include="..\..\src\Bing.Logs.NLog\Bing.Logs.NLog.csproj" />
<ProjectReference Include="..\..\src\Bing.Security\Bing.Security.csproj" />
<ProjectReference Include="..\..\src\Bing.Webs\Bing.Webs.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
57 changes: 57 additions & 0 deletions sample/Bing.Samples.Jwt/Controllers/OAuthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Bing.Security.Identity.JwtBearer;
using Bing.Webs.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace Bing.Samples.Jwt.Controllers
{
public class OAuthController : ApiControllerBase
{
/// <summary>
/// Jwt令牌构建器
/// </summary>
public IJsonWebTokenBuilder TokenBuilder { get; }

/// <summary>
/// 初始化一个<see cref="OAuthController"/>类型的实例
/// </summary>
/// <param name="tokenBuilder">Jwt令牌构建器</param>
public OAuthController(IJsonWebTokenBuilder tokenBuilder)
{
TokenBuilder = tokenBuilder;
}

/// <summary>
/// 登录
/// </summary>
/// <param name="request">请求</param>
[HttpPost("signIn")]
public async Task<IActionResult> SignInAsync([FromBody] LoginRequest request)
{
var payload = new Dictionary<string, string>();
payload["clientId"] = "66666";
payload["userId"] = Guid.NewGuid().ToString();
payload["username"] = request.UserName;
var result = await TokenBuilder.CreateAsync(payload);
return Success(result);
}

/// <summary>
/// 刷新令牌
/// </summary>
/// <param name="token">刷新令牌</param>
[HttpPost("refreshToken")]
public async Task<IActionResult> RefreshTokenAsync([FromBody] string token)
{
return Success(await TokenBuilder.RefreshAsync(token));
}
}

public class LoginRequest
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
24 changes: 24 additions & 0 deletions sample/Bing.Samples.Jwt/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Bing.Samples.Jwt
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
30 changes: 30 additions & 0 deletions sample/Bing.Samples.Jwt/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:44575",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Bing.Samples.Jwt": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
164 changes: 164 additions & 0 deletions sample/Bing.Samples.Jwt/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Bing.AspNetCore;
using Bing.Core;
using Bing.EasyCaching;
using Bing.Extensions.Swashbuckle.Configs;
using Bing.Extensions.Swashbuckle.Core;
using Bing.Extensions.Swashbuckle.Extensions;
using Bing.Extensions.Swashbuckle.Filters.Documents;
using Bing.Extensions.Swashbuckle.Filters.Operations;
using Bing.Logs.NLog;
using Bing.Security.Extensions;
using EasyCaching.Core;
using EasyCaching.CSRedis;
using EasyCaching.Serialization.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace Bing.Samples.Jwt
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

/// <summary>
/// 配置服务
/// </summary>
/// <param name="services">服务集合</param>
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices();
services.AddJwt(Configuration);
services.AddNLog();
// 添加EasyCaching缓存
services.AddCaching(options =>
{
options.UseCSRedis(config =>
{
// 互斥锁的存活时间。默认值:5000
config.LockMs = 5000;
// 预防缓存在同一时间全部失效,可以为每个key的过期时间添加一个随机的秒数。默认值:120秒
config.MaxRdSecond = 120;
// 是否开启日志。默认值:false
config.EnableLogging = false;
// 没有获取到互斥锁时的休眠时间。默认值:300毫秒
config.SleepMs = 300;
config.DBConfig = new CSRedisDBOptions()
{
ConnectionStrings = new List<string>()
{
Configuration.GetConnectionString("RedisConnection")
}
};
}).WithJson();
});

services.AddSwaggerCustom(CurrentSwaggerOptions);
services.AddBing<AspNetCoreBingModuleManager>();
return services.BuildServiceProvider();
}

/// <summary>
/// 配置请求管道
/// </summary>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseEasyCaching();
app.UseSwaggerCustom(CurrentSwaggerOptions);
ConfigRoute(app);
app.UseBing();
}

/// <summary>
/// 路由配置,支持区域
/// </summary>
private void ConfigRoute(IApplicationBuilder app)
{
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action=Index}/{id?}");
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
app.Run(context =>
{
context.Response.Redirect("/swagger");
return Task.CompletedTask;
});
}

/// <summary>
/// 项目接口文档配置
/// </summary>
private CustomSwaggerOptions CurrentSwaggerOptions = new CustomSwaggerOptions()
{
ProjectName = "Bing.Samples.Jwt 在线文档调试",
UseCustomIndex = true,
RoutePrefix = "swagger",
ApiVersions = new List<Extensions.Swashbuckle.Configs.ApiVersion>() { new Extensions.Swashbuckle.Configs.ApiVersion() { Description = "", Version = "v1" } },
SwaggerAuthorizations = new List<CustomSwaggerAuthorization>()
{
},
AddSwaggerGenAction = config =>
{
//config.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "Bing.Samples.Jwt.xml"), true);

config.OperationFilter<RequestHeaderOperationFilter>();
config.OperationFilter<ResponseHeadersOperationFilter>();
config.OperationFilter<FileParameterOperationFilter>();

// 授权组合
config.OperationFilter<SecurityRequirementsOperationFilter>();
config.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

#region 启用Swagger验证功能

// 启用Swagger验证功能,与AddSecurityDefinition方法指定的方案名称一致
config.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>()
{{"oauth2", new string[] { }}});

config.AddSecurityDefinition("oauth2", new ApiKeyScheme()
{
Description = "Token令牌,JWT授权(数据将在请求头中进行传输)在下方输入Bearer {token} 即可,注意两者之间有空格",
In = "header",
Name = "Authorization",
Type = "apiKey",
});

#endregion 启用Swagger验证功能

// 设置所有参数为驼峰式命名
config.DescribeAllParametersInCamelCase();
// 显示枚举描述
config.DocumentFilter<AddEnumDescriptionsDocumentFilter>();
// 显示首字母小写Url
config.ShowUrlMode();
},
UseSwaggerAction = config =>
{
},
UseSwaggerUIAction = config =>
{
config.InjectJavascript("/swagger/resources/jquery");
config.InjectStylesheet("/swagger/resources/swagger-common");
config.UseDefaultSwaggerUI();
}
};
}
}
9 changes: 9 additions & 0 deletions sample/Bing.Samples.Jwt/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
18 changes: 18 additions & 0 deletions sample/Bing.Samples.Jwt/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"RedisConnection": "192.168.0.66:6379,password=bing2019.00,poolsize=10,prefix=bing.samples:"
},
"JsonWebTokenOptions": {
"Secret": "2qyg4coej67uqrono0xdmx4y0il5dn5y7b72tlb3imba677ht1p1xlfcnh36mk5u3xzjktfara29axvzk85apfplun7oslbe1m20c148p5d519kja5wvg7lmn5v4a5ou",
"Issuer": "bing_identity",
"Audience": "bing_client",
"AccessExpireMinutes": 5,
"RefreshExpireMinutes": 6
},
"AllowedHosts": "*"
}
Loading

0 comments on commit dfd8493

Please sign in to comment.