diff --git a/Attributes/YYAuthAttribute.cs b/Attributes/YYAuthAttribute.cs new file mode 100644 index 0000000..08876d2 --- /dev/null +++ b/Attributes/YYAuthAttribute.cs @@ -0,0 +1,48 @@ +using System.Linq; +using Microsoft.AspNetCore.Mvc.Filters; +using YYApi.Communications; +using YYApi.Exceptions; + +namespace YYApi.Attributes +{ + /// + /// 检测登录中间件 + /// + public class YYAuthAttribute : ActionFilterAttribute + { + private string[] Types { get; } + + //默认是user登录类型 + public YYAuthAttribute() + { + Types = new[] { "user" }; + } + + //只检测一种用户类型的快捷方式 + public YYAuthAttribute(string type) + { + Types = new[] { type }; + } + + //设定特定类型的检测 + public YYAuthAttribute(string[] types) + { + Types = types; + } + + public override void OnActionExecuting(ActionExecutingContext context) + { + var loginInfo = (YYLoginItem)context.HttpContext.Items["LoginInfo"]; + //检测是否登录 + if (loginInfo == null) + { + throw new YYApiException(401); + } + //检测用户类型 + if (!Types.Contains(loginInfo.Type)) + { + throw new YYApiException(403); + } + } + } +} diff --git a/Helpers/ApiDoc.cs b/Attributes/YYDocAttribute.cs similarity index 72% rename from Helpers/ApiDoc.cs rename to Attributes/YYDocAttribute.cs index 4c713fb..b6cc66a 100644 --- a/Helpers/ApiDoc.cs +++ b/Attributes/YYDocAttribute.cs @@ -1,20 +1,20 @@ using Swashbuckle.AspNetCore.Annotations; -namespace YYApi.Helpers +namespace YYApi.Attributes { /// /// 快捷自定义接口文档类 /// - public class ApiDoc : SwaggerOperationAttribute + public class YYDocAttribute : SwaggerOperationAttribute { /// /// 定义接口说明 /// /// 接口分组 /// 接口名称 - public ApiDoc(string tag, string name) + public YYDocAttribute(string tag, string name) { - Tags = new[] {tag}; + Tags = new[] { tag }; Summary = name; // Consumes = new[] {"application/json"}; // Produces = new[] {"application/json"}; diff --git a/Communications/YYBaseRequest.cs b/Communications/YYBaseRequest.cs new file mode 100644 index 0000000..507c720 --- /dev/null +++ b/Communications/YYBaseRequest.cs @@ -0,0 +1,20 @@ +using System; +namespace YYApi.Communications +{ + /// + /// 只有ID的请求 + /// + public class YYIdOnlyRequest + { + public int Id { get; set; } + } + + /// + /// 基础分页请求 + /// + public class YYBasePageRequest + { + public int Page { get; set; } + public int Count { get; set; } + } +} diff --git a/Communications/Base.cs b/Communications/YYBaseResponse.cs similarity index 84% rename from Communications/Base.cs rename to Communications/YYBaseResponse.cs index 64d5726..04869e0 100644 --- a/Communications/Base.cs +++ b/Communications/YYBaseResponse.cs @@ -7,7 +7,7 @@ namespace YYApi.Communications /// /// 基础相应 /// - public class BaseResponse + public class YYBaseResponse { /// /// 错误代码 @@ -36,7 +36,7 @@ namespace YYApi.Communications /// /// 返回一个成功的空结果 /// - public BaseResponse() + public YYBaseResponse() { SetCode(200); } @@ -46,7 +46,7 @@ namespace YYApi.Communications /// 返回指定代码的描述 /// /// 错误代码 - public BaseResponse(int code) + public YYBaseResponse(int code) { SetCode(code); } @@ -56,7 +56,7 @@ namespace YYApi.Communications /// /// 错误代码 /// 错误信息 - public BaseResponse(int code, string message) + public YYBaseResponse(int code, string message) { SetCodeMsg(code, message); } @@ -104,7 +104,7 @@ namespace YYApi.Communications /// 动态内容分页 /// /// - public class BasePageResponse : BaseResponse + public class YYBasePageResponse : YYBaseResponse { /// /// 动态内容列表 @@ -122,31 +122,11 @@ namespace YYApi.Communications /// 动态Data返回 /// /// - public class BaseResponse : BaseResponse + public class YYBaseResponse : YYBaseResponse { /// /// 动态内容列表 /// public T Data { get; set; } } - - - //===========》请求《=============== - - /// - /// 只有ID的请求 - /// - public class IdOnlyRequest - { - public int Id { get; set; } - } - - /// - /// 基础分页请求 - /// - public class BasePageRequest - { - public int Page { get; set; } - public int Count { get; set; } - } } \ No newline at end of file diff --git a/Communications/YYLoginItem.cs b/Communications/YYLoginItem.cs new file mode 100644 index 0000000..44a7883 --- /dev/null +++ b/Communications/YYLoginItem.cs @@ -0,0 +1,14 @@ +using System; +namespace YYApi.Communications +{ + /// + /// 登录信息中间件 + /// + public class YYLoginItem + { + //登录用户的ID + public int Id { get; set; } + //登录用户来源 + public string Type { get; set; } + } +} diff --git a/Controllers/BaseController.cs b/Controllers/YYBaseController.cs similarity index 86% rename from Controllers/BaseController.cs rename to Controllers/YYBaseController.cs index d357835..750c7cd 100644 --- a/Controllers/BaseController.cs +++ b/Controllers/YYBaseController.cs @@ -1,9 +1,9 @@ using YYApi.Communications; -using YYApi.Helpers; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Linq; +using YYApi.Exceptions; namespace YYApi.Controllers { @@ -13,12 +13,12 @@ namespace YYApi.Controllers /// 2. 报错返回 /// 3. 错误回馈页面 /// - public class BaseController : Controller + public class YYBaseController : Controller { /// /// 当前登录用户的ID /// - protected LoginInfoItem LoginInfo => (LoginInfoItem)HttpContext.Items["LoginInfo"]; + protected YYLoginItem LoginInfo => (YYLoginItem)HttpContext.Items["LoginInfo"]; /// /// 验证请求参数 @@ -48,7 +48,7 @@ namespace YYApi.Controllers /// protected static void Error(int code, string message = "") { - throw new ApiException(code, message); + throw new YYApiException(code, message); } /// @@ -83,16 +83,16 @@ namespace YYApi.Controllers /// [HttpGet("exception/{code:int}")] [ApiExplorerSettings(IgnoreApi = true)] - public BaseResponse ExceptionHandler(int code) + public YYBaseResponse ExceptionHandler(int code) { - var response = new BaseResponse(); + var response = new YYBaseResponse(); response.SetCode(code); return response; } - protected BaseResponse UploadFile() + protected YYBaseResponse UploadFile() { - return new BaseResponse(); + return new YYBaseResponse(); } } } \ No newline at end of file diff --git a/Exceptions/YYApiException.cs b/Exceptions/YYApiException.cs new file mode 100644 index 0000000..08f9a3d --- /dev/null +++ b/Exceptions/YYApiException.cs @@ -0,0 +1,16 @@ +using System; +namespace YYApi.Exceptions +{ + /// + /// Api错误捕获异常 + /// + public class YYApiException : Exception + { + public int Code { get; } + + public YYApiException(int code, string message = "") : base(message) + { + Code = code; + } + } +} diff --git a/Extensions.cs b/Extensions.cs index cff3011..b71b72a 100644 --- a/Extensions.cs +++ b/Extensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerUI; +using YYApi.Middlewares; namespace YYApi { @@ -37,7 +38,7 @@ namespace YYApi public static IApplicationBuilder UseYYApi(this IApplicationBuilder builder, string title = "API文档", params SubmitMethod[] submitMethods) { - return builder.UseYYException().UseYYDoc(title, submitMethods).UseMiddleware(); + return builder.UseYYException().UseYYDoc(title, submitMethods).UseMiddleware(); } @@ -51,7 +52,7 @@ namespace YYApi /// public static IServiceCollection AddYYAuth(this IServiceCollection builder) { - return builder.AddScoped(); + return builder.AddScoped(); } /// @@ -91,7 +92,7 @@ namespace YYApi /// public static IApplicationBuilder UseYYException(this IApplicationBuilder builder) { - return builder.UseMiddleware(); + return builder.UseMiddleware(); } /// @@ -144,7 +145,7 @@ namespace YYApi /// public static IApplicationBuilder UseYYAuth(this IApplicationBuilder builder) { - return builder.UseMiddleware(); + return builder.UseMiddleware(); } diff --git a/Helpers/AuthMiddleware.cs b/Helpers/AuthMiddleware.cs deleted file mode 100644 index 285cf6e..0000000 --- a/Helpers/AuthMiddleware.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Linq; -using System.Text.Json; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Caching.Distributed; - -namespace YYApi.Helpers -{ - /// - /// 认证信息获取中间件 - /// - public class AuthMiddleware - { - private RequestDelegate Next { get; } - - public AuthMiddleware(RequestDelegate next) - { - Next = next; - } - - public Task Invoke(HttpContext httpContext, IDistributedCache cache) - { - string token = null; - if (httpContext.Request.Headers.ContainsKey("Token")) - { - token = httpContext.Request.Headers["Token"]; - } - - if (!string.IsNullOrEmpty(token)) - { - var login = cache.GetString(token); - if (login != null) - { - httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize(login)); - } - } - - return Next(httpContext); - } - } - - /// - /// 登录信息中间件 - /// - public class LoginInfoItem - { - //登录用户的ID - public int Id { get; set; } - //登录用户来源 - public string Type { get; set; } - } - - /// - /// 检测登录中间件 - /// - public class CheckAuthAttribute : ActionFilterAttribute - { - private string[] Types { get; } - - //默认是user登录类型 - public CheckAuthAttribute() - { - Types = new[] { "user" }; - } - - //只检测一种用户类型的快捷方式 - public CheckAuthAttribute(string type) - { - Types = new[] { type }; - } - - //设定特定类型的检测 - public CheckAuthAttribute(string[] types) - { - Types = types; - } - - public override void OnActionExecuting(ActionExecutingContext context) - { - var loginInfo = (LoginInfoItem)context.HttpContext.Items["LoginInfo"]; - //检测是否登录 - if (loginInfo == null) - { - throw new ApiException(401); - } - //检测用户类型 - if (!Types.Contains(loginInfo.Type)) - { - throw new ApiException(403); - } - } - } - - /// - /// 认证助手 - /// - public class Auth - { - private IDistributedCache Cache { get; } - - public Auth(IDistributedCache cache) - { - Cache = cache; - } - - /// - /// 产生一个Token记录并返回Token - /// - /// - /// - public string Set(int id, string type = "user") - { - var uuid = GetUUID(); - var loginItem = new LoginInfoItem - { - Id = id, - Type = type - }; - Cache.SetString(uuid, JsonSerializer.Serialize(loginItem)); - return uuid; - } - - private string GetUUID() - { - return Guid.NewGuid().ToString(); - } - } -} diff --git a/Helpers/YYAuth.cs b/Helpers/YYAuth.cs new file mode 100644 index 0000000..efd9a9e --- /dev/null +++ b/Helpers/YYAuth.cs @@ -0,0 +1,39 @@ +using System; +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Distributed; +using YYApi.Communications; + +namespace YYApi.Helpers +{ + /// + /// 认证助手 + /// + public class YYAuth + { + private IDistributedCache Cache { get; } + + public YYAuth(IDistributedCache cache) + { + Cache = cache; + } + + /// + /// 产生一个Token记录并返回Token + /// + /// + /// + public string Set(int id, string type = "user") + { + var uuid = Guid.NewGuid().ToString(); + var loginItem = new YYLoginItem + { + Id = id, + Type = type + }; + Cache.SetString(uuid, JsonSerializer.Serialize(loginItem)); + return uuid; + } + + } +} diff --git a/Helpers/Util.cs b/Helpers/YYUtil.cs similarity index 97% rename from Helpers/Util.cs rename to Helpers/YYUtil.cs index ce386af..b2cd178 100644 --- a/Helpers/Util.cs +++ b/Helpers/YYUtil.cs @@ -5,7 +5,7 @@ using System.Text.RegularExpressions; namespace YYApi.Helpers { - public static class Util + public static class YYUtil { /// /// 检测手机号是否正确 diff --git a/JobService/HFDashboardAuth.cs b/JobService/YYHFDashboardAuth.cs similarity index 97% rename from JobService/HFDashboardAuth.cs rename to JobService/YYHFDashboardAuth.cs index f8e1719..dcbdac4 100644 --- a/JobService/HFDashboardAuth.cs +++ b/JobService/YYHFDashboardAuth.cs @@ -20,11 +20,11 @@ namespace YYApi.JobService /// /// HangFire Dashboard Digest认证. /// - public class HFDashboardAuth : IDashboardAuthorizationFilter + public class YYHFDashboardAuth : IDashboardAuthorizationFilter { private IConfiguration _config { get; } private IDatabase _redis { get; } - public HFDashboardAuth(IConfiguration config, IDatabase redis) + public YYHFDashboardAuth(IConfiguration config, IDatabase redis) { _redis = redis; _config = config; diff --git a/JobService/JobDashboardConfig.cs b/JobService/YYJobDashboardConfig.cs similarity index 100% rename from JobService/JobDashboardConfig.cs rename to JobService/YYJobDashboardConfig.cs diff --git a/JobService/JobStorage.cs b/JobService/YYJobStorage.cs similarity index 100% rename from JobService/JobStorage.cs rename to JobService/YYJobStorage.cs diff --git a/Middlewares/YYAuthMiddleware.cs b/Middlewares/YYAuthMiddleware.cs new file mode 100644 index 0000000..77b3603 --- /dev/null +++ b/Middlewares/YYAuthMiddleware.cs @@ -0,0 +1,41 @@ +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Distributed; +using YYApi.Communications; + +namespace YYApi.Middlewares +{ + /// + /// 认证信息获取中间件 + /// + public class YYAuthMiddleware + { + private RequestDelegate Next { get; } + + public YYAuthMiddleware(RequestDelegate next) + { + Next = next; + } + + public Task Invoke(HttpContext httpContext, IDistributedCache cache) + { + string token = null; + if (httpContext.Request.Headers.ContainsKey("Token")) + { + token = httpContext.Request.Headers["Token"]; + } + + if (!string.IsNullOrEmpty(token)) + { + var login = cache.GetString(token); + if (login != null) + { + httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize(login)); + } + } + + return Next(httpContext); + } + } +} diff --git a/Helpers/ExceptionMiddleware.cs b/Middlewares/YYExceptionMiddleware.cs similarity index 64% rename from Helpers/ExceptionMiddleware.cs rename to Middlewares/YYExceptionMiddleware.cs index 80bac57..8dd84be 100644 --- a/Helpers/ExceptionMiddleware.cs +++ b/Middlewares/YYExceptionMiddleware.cs @@ -2,20 +2,20 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using YYApi.Communications; -using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; +using YYApi.Exceptions; -namespace YYApi.Helpers +namespace YYApi.Middlewares { /// /// 异常处理中间件 /// - public class ExceptionMiddleware + public class YYExceptionMiddleware { private RequestDelegate Next { get; } - private ILogger Log { get; } + private ILogger Log { get; } - public ExceptionMiddleware(RequestDelegate next, ILogger log) + public YYExceptionMiddleware(RequestDelegate next, ILogger log) { Log = log; Next = next; @@ -23,12 +23,12 @@ namespace YYApi.Helpers public async Task InvokeAsync(HttpContext context) { - var response = new BaseResponse(); + var response = new YYBaseResponse(); try { await Next(context); } - catch (ApiException ex) + catch (YYApiException ex) { response.SetCodeMsg(ex.Code, ex.Message); ErrorResponse(context, response); @@ -47,25 +47,11 @@ namespace YYApi.Helpers /// /// /// - private void ErrorResponse(HttpContext context, BaseResponse response) + private void ErrorResponse(HttpContext context, YYBaseResponse response) { context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "application/json"); context.Response.WriteAsync(response.ToString()); } } - - - /// - /// Api错误捕获异常 - /// - public class ApiException : Exception - { - public int Code { get; } - - public ApiException(int code, string message = "") : base(message) - { - Code = code; - } - } } \ No newline at end of file diff --git a/README.md b/README.md index 21ad45b..f9448d1 100644 --- a/README.md +++ b/README.md @@ -27,28 +27,28 @@ namespace Controllers ```C# #Startup.cs - services.AddApiDoc("文档名称", "文档描述"); + services.AddYYDoc("文档名称", "文档描述"); - app.UseApiDoc("名称",SubmitMethod[]) + app.UseYYDoc("名称",SubmitMethod[]) #控制器中可以直接使用特性 - [ApiDoc("分组","名称")] + [YYDoc("分组","名称")] ``` 3. 简单的基于Redis的登录TOKEN服务 ```C# #Startup.cs -service.AddAuth(); +service.AddYYAuth(); ``` 添加时候, 可以从DI中获取 Auth 类,调用 Auth.Set(int,string) 将用户ID/类型和生成的Token绑定,本方法返回缓存中的Key名称 ```C# #Startup.cs -app.UseAuthMiddleware(); +app.UseYYAuth(); ``` -调用本中间件,然后再需要登录认证的地方,使用 [CheckAuth] 特性,即可完成检测登录相关的操作, +调用本中间件,然后再需要登录认证的地方,使用 [YYAuth] 特性,即可完成检测登录相关的操作, 如果需要获取用户的ID, 只需要 直接使用 LoginId 属性即可获取 4. 统一返回 @@ -60,5 +60,5 @@ app.UseAuthMiddleware(); ```C# #Startup.cs -app.UseExceptionMiddleware(); +app.UseYYException(); ``` \ No newline at end of file diff --git a/YYApi.csproj b/YYApi.csproj index c52780e..48baeb8 100644 --- a/YYApi.csproj +++ b/YYApi.csproj @@ -18,6 +18,9 @@ + + +