using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeTax.CommonLibrary.Models.Enum;

namespace MerchantsApi.Filters
{
    public class MerchantAuthorizeAttribute : AuthorizeFilter
    {
        private static AuthorizationPolicy _policy_ = new AuthorizationPolicy(new[] { new DenyAnonymousAuthorizationRequirement() }, new string[] { });

        public MerchantAuthorizeAttribute() : base(_policy_)
        { }

        public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (string.IsNullOrEmpty(context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "userid")?.Value))
            {
                context.Result = new JsonResult(new WeTax.CommonLibrary.Models.WebApiResult(ApiResultCode.Fail, "请登录"));
            }
            await base.OnAuthorizationAsync(context);
        }
    }
}
            services.AddMvc(options =>
            {
                options.Filters.Add<MerchantAuthorizeAttribute>();
                //options.Filters.Add<AuthExceptionFilter>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

 

posted on 2019-06-06 13:41  chester·chen  阅读(1278)  评论(0编辑  收藏  举报