.Net Core 特性 获取Cookie,未登录跳转登录界面

特性:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json.Linq;
using System.Net;
using WaterCloud.Entity.SystemManage;

namespace OPAC.App_Start.Handler
{

    public class AdminAuthorizeAttribute : TypeFilterAttribute
    {
       
        public AdminAuthorizeAttribute() : base(typeof(AuthorizeWithCookieFilter))
        {
        }

        private class AuthorizeWithCookieFilter : IAsyncAuthorizationFilter
        {
            private readonly IHttpContextAccessor _httpContextAccessor;

            public AuthorizeWithCookieFilter(IHttpContextAccessor httpContextAccessor)
            {
                _httpContextAccessor = httpContextAccessor;
            }

            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                var request = context.HttpContext.Request;
                var response = context.HttpContext.Response;
                UserEntity entity = new UserEntity();
                var cookie = request.Cookies["adminlogin"];
                if (cookie != null)
                {
                    string json = WebUtility.UrlDecode(cookie);
                    if (!string.IsNullOrEmpty(json))
                    {
                        JObject jsonObject = JObject.Parse(json);

                        // 获取AdminCode的值  
                        entity.F_Account = (string)jsonObject["AdminCode"];
                        entity.F_Description = (string)jsonObject["AreaInfo"];

                    }
                }
                if (entity.F_Account == null || entity.F_Description == null)
                {
                    // 如果 Cookie 不存在或无效,重定向到登录页面或返回未授权响应
                    response.StatusCode = StatusCodes.Status302Found; // 使用302重定向状态码
                    response.Headers["Location"] = "/Admin/Login";
                    await response.WriteAsync("Redirecting to login page...");
                    context.Result = new UnauthorizedResult();
                }

            }

            private bool IsValidLoginCookie(string cookieValue)
            {
                // 在这里添加你的 Cookie 验证逻辑,例如解密和验证签名等
                // 这里只是一个示例,实际验证逻辑需要根据你的需求来实现
                return cookieValue == "valid-cookie-value"; // 替换为实际的验证逻辑
            }
        }
    }
}

使用:

  [AdminAuthorize]
  [HttpGet]
  public ActionResult UserSetting()
  {
      return View();
  }

 

posted on 2024-12-16 11:00  RookieBoy666  阅读(7)  评论(0编辑  收藏  举报