Skip to content

Commit

Permalink
1.新增权限相关整合
Browse files Browse the repository at this point in the history
2.修复部分类库问题
  • Loading branch information
AprilBlank committed Nov 10, 2019
1 parent 13e6439 commit ce13e02
Show file tree
Hide file tree
Showing 21 changed files with 760 additions and 18 deletions.
3 changes: 3 additions & 0 deletions April.Simple.WebApi/April.Simple.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
</ItemGroup>

Expand Down
13 changes: 13 additions & 0 deletions April.Simple.WebApi/April.Simple.WebApi.csproj.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Controller</Controller_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ControllerDialogWidth>600</WebStackScaffolding_ControllerDialogWidth>
<WebStackScaffolding_IsLayoutPageSelected>True</WebStackScaffolding_IsLayoutPageSelected>
<WebStackScaffolding_IsPartialViewSelected>False</WebStackScaffolding_IsPartialViewSelected>
<WebStackScaffolding_IsReferencingScriptLibrariesSelected>True</WebStackScaffolding_IsReferencingScriptLibrariesSelected>
<WebStackScaffolding_LayoutPageFile />
<WebStackScaffolding_IsAsyncSelected>False</WebStackScaffolding_IsAsyncSelected>
</PropertyGroup>
</Project>
68 changes: 68 additions & 0 deletions April.Simple.WebApi/Controllers/LoginController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using April.Util;
using April.Util.Config;
using April.Util.Entities.Admin;
using April.Util.Entities.Request;
using April.Util.Entities.Response;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace April.Simple.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[HttpPost]
public async Task<ResponseDataEntity> Login(LoginFormEntity formEntity)
{
if (string.IsNullOrEmpty(formEntity.LoginName) || string.IsNullOrEmpty(formEntity.Password))
{
return ResponseUtil.Fail("请输入账号密码");
}
if (formEntity.LoginName == "admin")
{
//这里实际应该通过db获取管理员
string password = EncryptUtil.MD5Encrypt(formEntity.Password, AprilConfig.SecurityKey);
if (password == "B092956160CB0018")
{
//获取管理员相关权限,同样是db获取,这里只做展示
AdminEntity admin = new AdminEntity
{
UserName = "超级管理员",
Avator = "",
IsSuperManager = true,
TokenType = (int)AprilEnums.TokenType.Web
};
string token = TokenUtil.GetToken(admin, out string expiretimestamp);
int expiretime = 0;
int.TryParse(expiretimestamp, out expiretime);
//可以考虑记录登录日志等其他信息
return ResponseUtil.Success("", new { username = admin.UserName, avator = admin.Avator, token = token, expire = expiretime });
}
}
else if (formEntity.LoginName == "test")
{
//这里做权限演示
AdminEntity admin = new AdminEntity
{
UserName = "测试",
Avator = "",
TokenType = (int)AprilEnums.TokenType.Web
};
admin.Controllers.Add("weatherforecast");
admin.Permissions.Add("weatherforecast_log");//控制器_事件(Add,Update...)
string token = TokenUtil.GetToken(admin, out string expiretimestamp);
int expiretime = 0;
int.TryParse(expiretimestamp, out expiretime);
//可以考虑记录登录日志等其他信息
return ResponseUtil.Success("", new { username = admin.UserName, avator = admin.Avator, token = token, expire = expiretime });
}
//这里其实已经可以考虑验证码相关了,但是这是示例工程,后续可持续关注我,会有基础工程(带权限)的实例公开
return ResponseUtil.Fail("账号密码错误");
}
}
}
2 changes: 2 additions & 0 deletions April.Simple.WebApi/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ public FileContentResult Code(int type)

[HttpGet]
[Route("LogLevel")]
[AprilPermission("weatherforecast", "set")]
public ResponseDataEntity Set()
{
//日志等级由系统维护,通过配置参数获取
Expand All @@ -85,6 +86,7 @@ public ResponseDataEntity Set()

[HttpGet]
[Route("Log")]
[AprilPermission("weatherforecast","log")]
public ResponseDataEntity Log()
{
LogUtil.Debug("Debug");
Expand Down
5 changes: 5 additions & 0 deletions April.Simple.WebApi/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using April.Util;
using April.Util.Config;
using April.Util.Middles;
using April.Util.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand Down Expand Up @@ -86,6 +87,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseDeveloperExceptionPage();
}



#region Swagger
app.UseSwagger();
app.UseSwaggerUI(options =>
Expand All @@ -97,6 +100,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
#endregion
app.UseSession();

app.UseMiddleware<AprilAuthorizationMiddleware>();

app.UseHttpsRedirection();

app.UseRouting();
Expand Down
7 changes: 6 additions & 1 deletion April.Simple.WebApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
"LogLevel": "DEBUG",
"CommonSettings": {
"SecurityKey": "aprilapi",
"IsOpenWatch": "true"
"IsOpenWatch": "true",
"WebExpire": "1",
"AppExpire": "2",
"MiniProgramExpire": "72",
"OtherExpire": "2",
"AllowUrl": "/index.html,/swagger/v1/swagger.json,/api/Login"
},
"FilePath": {
"Log4": "resource/config/log4net.config"
Expand Down
45 changes: 45 additions & 0 deletions April.Util/Aop/AprilPermissionAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using April.Util.Entities.Admin;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace April.Util.Aop
{
public class AprilPermissionAttribute : Attribute, IActionFilter
{

public string Permission;
public string Controller;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="_controller">控制器</param>
/// <param name="_permission">接口事件</param>
public AprilPermissionAttribute(string _controller, string _permission)
{
Permission = _permission;
Controller = _controller;
}

public void OnActionExecuted(ActionExecutedContext context)
{
LogUtil.Debug("AprilPermission OnActionExecuted");
}
public void OnActionExecuting(ActionExecutingContext context)
{
AdminEntity admin = TokenUtil.GetUserByToken();
if (admin == null || admin.ExpireTime <= DateTime.Now)
{
context.Result = new ObjectResult(new { msg = "未登录", code = -2 });
}
if (!admin.IsSuperManager)
{
string controller_permission = $"{Controller}_{Permission}";
if (!admin.Controllers.Contains(Controller) || !admin.Permissions.Contains(controller_permission))
{
context.Result = new ObjectResult(new { msg = "无权访问", code = 401 });
}
}
}
}
}
3 changes: 2 additions & 1 deletion April.Util/April.Util.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
Expand All @@ -13,6 +13,7 @@
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
Expand Down
98 changes: 98 additions & 0 deletions April.Util/Config/AprilConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,104 @@ public static bool IsOpenWatch
}
#endregion

#region========权限登录========
private static string _TokenSecretFormat = string.Empty;
private static string _TokenCacheType = string.Empty;
private static string _AllowSliding = string.Empty;
private static string _AllowMuiltiLogin = string.Empty;
/// <summary>
/// token加密串格式
/// </summary>
public static string TokenSecretFormat
{
get
{
if (string.IsNullOrEmpty(_TokenSecretFormat))
{
_TokenSecretFormat = Configuration["LoginSettings:TokenSecretFormat"];
}
if (string.IsNullOrEmpty(_TokenSecretFormat))
{
//不设置采取默认
_TokenSecretFormat = "april{id}&&&&{ts}";
}
return _TokenSecretFormat;
}
}
/// <summary>
/// 存储Token方式
/// </summary>
public static AprilEnums.TokenCacheType TokenCacheType
{
get
{
if (string.IsNullOrEmpty(_TokenCacheType))
{
_TokenCacheType = Configuration["LoginSettings:TokenCacheType"];
}
if (string.IsNullOrEmpty(_TokenCacheType))
{
//不设置采取默认
_TokenCacheType = "Session";
}
switch (_TokenCacheType.ToLower())
{
case "cookie":
return AprilEnums.TokenCacheType.Cookie;
break;
case "cache":
return AprilEnums.TokenCacheType.Cache;
break;
case "session":
return AprilEnums.TokenCacheType.Session;
break;
case "redis":
return AprilEnums.TokenCacheType.Redis;
break;
default:
return AprilEnums.TokenCacheType.Session;
break;
}
}
}
/// <summary>
/// 允许滑动过期
/// </summary>
public static bool AllowSliding
{
get
{
if (string.IsNullOrEmpty(_AllowSliding))
{
_AllowSliding = Configuration["LoginSettings:AllowSliding"];
}
if (!string.IsNullOrEmpty(_AllowSliding) && _AllowSliding.ToLower() == "true")
{
return true;
}
return false;
}
}
/// <summary>
/// 多端登录
/// </summary>
public static bool AllowMuiltiLogin
{
get
{
if (string.IsNullOrEmpty(_AllowMuiltiLogin))
{
_AllowMuiltiLogin = Configuration["LoginSettings:AllowMuiltiLogin"];
}
if (!string.IsNullOrEmpty(_AllowMuiltiLogin) && _AllowMuiltiLogin.ToLower() == "true")
{
return true;
}
return false;
}
}
#endregion

#region ========当前页面========
/// <summary>
/// 当前请求页面
Expand Down
20 changes: 20 additions & 0 deletions April.Util/Config/AprilEnums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,26 @@ public enum LogLevel
ERROR,
FATAL
}
/// <summary>
/// 登录方式
/// </summary>
public enum TokenType
{
Web,
App,
MiniProgram,
Other
}
/// <summary>
/// 管理员缓存获取方式
/// </summary>
public enum TokenCacheType
{
Cookie,
Cache,
Session,
Redis
}

}
}
Loading

0 comments on commit ce13e02

Please sign in to comment.