添加jwt认证模块

This commit is contained in:
橙子
2023-01-18 19:42:13 +08:00
parent eb1a86e5b2
commit fc74a000a6
12 changed files with 309 additions and 2 deletions

View File

@@ -0,0 +1,7 @@
namespace Yi.Framework.Data
{
public class Class1
{
}
}

View File

@@ -0,0 +1,106 @@
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Yi.Framework.Data
//{
// public class DataFilter : IDataFilter
// {
// private readonly ConcurrentDictionary<Type, object> _filters;
// private readonly IServiceProvider _serviceProvider;
// public DataFilter(IServiceProvider serviceProvider)
// {
// _serviceProvider = serviceProvider;
// _filters = new ConcurrentDictionary<Type, object>();
// }
// public IDisposable Enable<TFilter>()
// where TFilter : class
// {
// return GetFilter<TFilter>().Enable();
// }
// public IDisposable Disable<TFilter>()
// where TFilter : class
// {
// return GetFilter<TFilter>().Disable();
// }
// public bool IsEnabled<TFilter>()
// where TFilter : class
// {
// return GetFilter<TFilter>().IsEnabled;
// }
// private IDataFilter<TFilter> GetFilter<TFilter>()
// where TFilter : class
// {
// return _filters.GetOrAdd(
// typeof(TFilter),
// valueFactory: (k) => _serviceProvider.GetRequiredService<IDataFilter<TFilter>>()
// ) as IDataFilter<TFilter>;
// }
// }
// public class DataFilter<TFilter> : IDataFilter<TFilter>
// where TFilter : class
// {
// public bool IsEnabled
// {
// get
// {
// EnsureInitialized();
// return _filter.Value.IsEnabled;
// }
// }
// private readonly AbpDataFilterOptions _options;
// private readonly AsyncLocal<DataFilterState> _filter;
// public DataFilter(IOptions<AbpDataFilterOptions> options)
// {
// _options = options.Value;
// _filter = new AsyncLocal<DataFilterState>();
// }
// public IDisposable Enable()
// {
// if (IsEnabled)
// {
// return NullDisposable.Instance;
// }
// _filter.Value.IsEnabled = true;
// return new DisposeAction(() => Disable());
// }
// public IDisposable Disable()
// {
// if (!IsEnabled)
// {
// return NullDisposable.Instance;
// }
// _filter.Value.IsEnabled = false;
// return new DisposeAction(() => Enable());
// }
// private void EnsureInitialized()
// {
// if (_filter.Value != null)
// {
// return;
// }
// _filter.Value = _options.DefaultStates.GetOrDefault(typeof(TFilter))?.Clone() ?? new DataFilterState(true);
// }
// }
//}

View File

@@ -0,0 +1,31 @@
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Yi.Framework.Data
//{
// public interface IDataFilter<TFilter>
// where TFilter : class
// {
// IDisposable Enable();
// IDisposable Disable();
// bool IsEnabled { get; }
// }
// public interface IDataFilter
// {
// IDisposable Enable<TFilter>()
// where TFilter : class;
// IDisposable Disable<TFilter>()
// where TFilter : class;
// bool IsEnabled<TFilter>()
// where TFilter : class;
// }
//}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -43,9 +43,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Core.Sqlsugar"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Core.AutoMapper", "src\framework\Yi.Framework.Core.AutoMapper\Yi.Framework.Core.AutoMapper.csproj", "{DFD34702-2EF6-4ECC-AE6E-9A1A3885BD26}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Office.Excel", "src\module\Yi.Framework.Office.Excel\Yi.Framework.Office.Excel.csproj", "{4EEC6607-F0D8-4277-9463-104DA7E184B6}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Office.Excel", "src\module\Yi.Framework.Office.Excel\Yi.Framework.Office.Excel.csproj", "{4EEC6607-F0D8-4277-9463-104DA7E184B6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.WeChatPay", "src\module\Yi.Framework.WeChatPay\Yi.Framework.WeChatPay.csproj", "{588D0DA9-303A-4FF0-A2D1-83037E2B269F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.WeChatPay", "src\module\Yi.Framework.WeChatPay\Yi.Framework.WeChatPay.csproj", "{588D0DA9-303A-4FF0-A2D1-83037E2B269F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Data", "Yi.Framework.Data\Yi.Framework.Data.csproj", "{DEE07142-32CE-4B5F-A5A3-452064EBF4A2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Authentication.JwtBearer", "src\framework\Yi.Framework.Authentication.JwtBearer\Yi.Framework.Authentication.JwtBearer.csproj", "{D40C583D-58BE-422D-9A57-94DECB751EB4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -129,6 +133,14 @@ Global
{588D0DA9-303A-4FF0-A2D1-83037E2B269F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{588D0DA9-303A-4FF0-A2D1-83037E2B269F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{588D0DA9-303A-4FF0-A2D1-83037E2B269F}.Release|Any CPU.Build.0 = Release|Any CPU
{DEE07142-32CE-4B5F-A5A3-452064EBF4A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DEE07142-32CE-4B5F-A5A3-452064EBF4A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DEE07142-32CE-4B5F-A5A3-452064EBF4A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DEE07142-32CE-4B5F-A5A3-452064EBF4A2}.Release|Any CPU.Build.0 = Release|Any CPU
{D40C583D-58BE-422D-9A57-94DECB751EB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D40C583D-58BE-422D-9A57-94DECB751EB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D40C583D-58BE-422D-9A57-94DECB751EB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D40C583D-58BE-422D-9A57-94DECB751EB4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -153,6 +165,8 @@ Global
{DFD34702-2EF6-4ECC-AE6E-9A1A3885BD26} = {5F2B846D-96CE-400A-878E-220498F4EE31}
{4EEC6607-F0D8-4277-9463-104DA7E184B6} = {EEF5F221-0E32-4A3D-B647-B4B5E7305806}
{588D0DA9-303A-4FF0-A2D1-83037E2B269F} = {EEF5F221-0E32-4A3D-B647-B4B5E7305806}
{DEE07142-32CE-4B5F-A5A3-452064EBF4A2} = {5F2B846D-96CE-400A-878E-220498F4EE31}
{D40C583D-58BE-422D-9A57-94DECB751EB4} = {5F2B846D-96CE-400A-878E-220498F4EE31}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6C1A3808-0F4F-43FB-A9FE-5F27A3BB2ECF}

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Yi.Framework.AspNetCore\Yi.Framework.AspNetCore.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,111 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System.Net;
using System.Security.Claims;
namespace Yi.Framework.Authentication.JwtBearer
{
public class YiJwtAuthenticationHandler : IAuthenticationHandler
{
public YiJwtAuthenticationHandler()
{
}
public const string YiJwtSchemeName = "YiJwtAuth";
private AuthenticationScheme _scheme;
private HttpContext _context;
/// <summary>
/// 初始化数据
/// </summary>
/// <param name="scheme"></param>
/// <param name="context"></param>
/// <returns></returns>
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
_scheme = scheme;
_context = context;
return Task.CompletedTask;
}
/// <summary>
/// 生成认证票据
/// </summary>
/// <param name="name"></param>
/// <param name="role"></param>
/// <returns></returns>
private AuthenticationTicket GetAuthTicket(string name, string role)
{
var claimsIdentity = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.Role, role),
}, YiJwtSchemeName);
var principal = new ClaimsPrincipal(claimsIdentity);
return new AuthenticationTicket(principal, _scheme.Name);
}
/// <summary>
/// 处理操作
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Task<AuthenticateResult> AuthenticateAsync()
{
AuthenticateResult result;
_context.Request.Headers.TryGetValue("Authorization", out StringValues values);
string valStr = values.ToString();
if (!string.IsNullOrWhiteSpace(valStr))
{
//认证模拟basic认证cusAuth YWRtaW46YWRtaW4=
string[] authVal = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(valStr.Substring(YiJwtSchemeName.Length + 1))).Split(':');
//var loginInfo = new Dto.LoginDto() { Username = authVal[0], Password = authVal[1] };
//var validVale = _userService.IsValid(loginInfo);
bool validVale = true;
if (!validVale)
result = AuthenticateResult.Fail("未登陆");
else
{
//这里应该将token进行效验然后加入解析的claim中即可
var ticket = GetAuthTicket("cc", "admin");
result = AuthenticateResult.Success(ticket);
}
}
else
{
result = AuthenticateResult.Fail("未登陆");
}
return Task.FromResult(result);
}
/// <summary>
/// 未登录时的处理
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Task ChallengeAsync(AuthenticationProperties? properties)
{
_context.Request.Headers.TryGetValue("Authorization", out StringValues values);
_context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
/// <summary>
/// 权限不足的处理
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Task ForbidAsync(AuthenticationProperties? properties)
{
_context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return Task.CompletedTask;
}
}
}

View File

@@ -15,6 +15,7 @@ using Yi.Framework.Domain.Student.Entities;
using Yi.Framework.Ddd.Services;
using Yi.Framework.Core.Attributes;
using Yi.Framework.Uow;
using Microsoft.AspNetCore.Authorization;
namespace Yi.Framework.Application.Student
{
@@ -41,6 +42,7 @@ namespace Yi.Framework.Application.Student
/// Uow
/// </summary>
/// <returns></returns>
[Authorize]
public async Task<StudentGetOutputDto> PostUow()
{
StudentGetOutputDto res = new();

View File

@@ -1,4 +1,5 @@
using AspNetCore.Microsoft.AspNetCore.Hosting;
using Yi.Framework.Authentication.JwtBearer;
using Yi.Framework.Core.Autofac.Extensions;
using Yi.Framework.Core.Autofac.Modules;
using Yi.Framework.Core.Extensions;
@@ -13,6 +14,12 @@ builder.WebHost.UseStartUrlsServer(builder.Configuration);
//<2F><><EFBFBD><EFBFBD>ģ<EFBFBD><C4A3>
builder.UseYiModules(typeof(YiFrameworkWebModule));
builder.Services.AddAuthentication(YiJwtAuthenticationHandler.YiJwtSchemeName);
builder.Services.AddAuthentication(option =>
{
option.AddScheme<YiJwtAuthenticationHandler>(YiJwtAuthenticationHandler.YiJwtSchemeName, YiJwtAuthenticationHandler.YiJwtSchemeName);
});
//<2F><><EFBFBD><EFBFBD>autofacģ<63><C4A3>,<2C><>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD>ģ<EFBFBD><C4A3>
builder.Host.ConfigureAutoFacContainer(container =>
{
@@ -25,6 +32,9 @@ var t = app.Services.GetService<Test2Entity>();
//ȫ<>ִ<EFBFBD><D6B4><EFBFBD><EFBFBD>м<EFBFBD><D0BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
app.UseErrorHandlingServer();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@@ -33,3 +33,6 @@
2023:01:17-23:24:07本次运行启动时间为1836毫秒
2023:01:17-23:29:20本次运行启动时间为1958毫秒
2023:01:17-23:45:25本次运行启动时间为2016毫秒
2023:01:18-19:34:47本次运行启动时间为2631毫秒
2023:01:18-19:36:58本次运行启动时间为2551毫秒
2023:01:18-19:40:12本次运行启动时间为1978毫秒

View File

@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\framework\Yi.Framework.Authentication.JwtBearer\Yi.Framework.Authentication.JwtBearer.csproj" />
<ProjectReference Include="..\..\src\framework\Yi.Framework.Core.Autofac\Yi.Framework.Core.Autofac.csproj" />
<ProjectReference Include="..\Yi.Framework.Application\Yi.Framework.Application.csproj" />
<ProjectReference Include="..\Yi.Framework.Sqlsugar\Yi.Framework.Sqlsugar.csproj" />