zhaolei
2020-11-20 4a2e5b9a21940f11757be37d99f0944e240e908b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using Bootstrap.Security.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using System.Linq;
using System.Threading.Tasks;
 
namespace Microsoft.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// BootstrapAdmin 后台权限认证过滤器
    /// </summary>
    public class BootstrapAdminAuthorizeFilter : IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 异步授权方法
        /// </summary>
        /// <param name="context">过滤器上下文</param>
        /// <returns></returns>
        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // 允许匿名访问时忽略
            // 管理员组访问时忽略
            // api 请求忽略
            // Razor 请求忽略
            if (context.ActionDescriptor.EndpointMetadata.Any(meta => meta is IAllowAnonymous || meta is ApiControllerAttribute) ||
#if !NETSTANDARD2_0
                context.ActionDescriptor.EndpointMetadata.Any(meta => meta is PageRouteMetadata) ||
#endif
                context.HttpContext.User.IsInRole("Administrators")) return Task.CompletedTask;
 
            // 判断菜单授权
            var url = $"~/{context.ActionDescriptor.RouteValues["controller"]}/{context.ActionDescriptor.RouteValues["action"]}";
            if (!AuthenticationExtensions.RetrieveRolesByUrl(url, BootstrapAppContext.AppId).Any(context.HttpContext.User.IsInRole)) context.Result = new ForbidResult();
            return Task.CompletedTask;
        }
    }
}