Skip to content

Commit

Permalink
新增Security
Browse files Browse the repository at this point in the history
  • Loading branch information
my6521 committed Oct 14, 2023
1 parent 8fa0656 commit a699855
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/WWB.UnifyApi/Security/IPermissionValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace WWB.UnifyApi.Security
{
public interface IPermissionValidator
{
PermissionValidResult Valid(string permission);
}
}
12 changes: 12 additions & 0 deletions src/WWB.UnifyApi/Security/PermissionAuthorizeAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;

namespace WWB.UnifyApi.Security
{
public class PermissionAuthorizeAttribute : TypeFilterAttribute
{
public PermissionAuthorizeAttribute(string permission) : base(typeof(RequirementPermissionFilter))
{
Arguments = new object[] { permission };
}
}
}
8 changes: 8 additions & 0 deletions src/WWB.UnifyApi/Security/PermissionValidResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace WWB.UnifyApi.Security
{
public class PermissionValidResult
{
public bool IsSuccess { get; set; }
public string Error { get; set; }
}
}
46 changes: 46 additions & 0 deletions src/WWB.UnifyApi/Security/RequirementPermissionFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace WWB.UnifyApi.Security
{
public class RequirementPermissionFilter : IAuthorizationFilter
{
private readonly string _permission;

public RequirementPermissionFilter(string permission)
{
_permission = permission;
}

public void OnAuthorization(AuthorizationFilterContext context)
{
var endpoint = context.HttpContext.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint != null && endpoint.Metadata.GetMetadata<AllowAnonymousAttribute>() != null)
{
return;
}
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new StatusCodeResult(401);
return;
}

var validator = context.HttpContext.RequestServices.GetService<IPermissionValidator>();

if (validator == null)
{
throw new Exception("权限验证失败:未找到验证接口");
}

var validResult = validator.Valid(_permission);
if (!validResult.IsSuccess)
{
throw new Exception($"权限验证失败:{validResult.Error}");
}
}
}
}

0 comments on commit a699855

Please sign in to comment.