设为首页 加入收藏

TOP

.Net Core权限认证基于Cookie的认证&授权.Scheme、Policy扩展(一)
2019-09-30 16:48:52 】 浏览:176
Tags:.Net Core 权限 认证 基于 Cookie 授权 .Scheme Policy 扩展

在身份认证中,如果某个Action需要权限才能访问,最开始的想法就是,哪个Action需要权限才能访问,我们写个特性标注到上面即可,[TypeFilter(typeof(CustomAuthorizeActionFilterAttribute))]

/// <summary>
 /// 这是一个Action的Filter`  但是用作权限验证
 /// </summary>
 public class CustomAuthorizeActionFilterAttribute : Attribute, IActionFilter
 {
     private ILogger<CustomAuthorizeActionFilterAttribute> _logger = null;
     public CustomAuthorizeActionFilterAttribute(ILogger<CustomAuthorizeActionFilterAttribute> logger)
     {
         this._logger = logger;
     }

     public void OnActionExecuting(ActionExecutingContext context)
     {
         //取出Session
         var strUser = context.HttpContext.Session.GetString("CurrentUser");
         if (!string.IsNullOrWhiteSpace(strUser))
         {
             CurrentUser currentUser = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentUser>(strUser);
             _logger.LogDebug($"userName is {currentUser.Name}");
         }
         else
         { 
             context.Result = new RedirectResult("~/Fourth/Login");
         }
          
     }
     public void OnActionExecuted(ActionExecutedContext context)
     {
         //context.HttpContext.Response.WriteAsync("ActionFilter Executed!");
         Console.WriteLine("ActionFilter Executed!");
         //this._logger.LogDebug("ActionFilter Executed!");
     }

 }

当然了,要先在服务里面使用Session的服务==》services.AddSession();

但是这样不好。.Net Core框架下,有一个特性Authorize,当我们需要使用的时候,在某个Action上面标注即可

 [Authorize]
 public IActionResult Center()
 {
     return Content("Center");
 }

我们来运行看一下,会报异常

 

 因为我们没有使用服务,在.Net Core下面,是默认不启用授权过滤器的。这也是.Net Core框架的一个好处,我们需要的时候才进行使用。框架做的少,更轻。

下面我们在服务里面使用授权过滤器的服务

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
    AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
o =>
    {
        o.LoginPath = new PathString("/Home/Login");
    });

再次浏览刚才的页面,这样就会请求到登录页面,会把刚才请求的页面当做一个参数

 

当然也要使用app.UseAuthentication();这个中间件。

在.Net Core里面,保存登录状态,也是通过Cookie的方式。使用ClaimsIdentity与ClaimsPrincipal

public ActionResult Login(string name, string password)
{
    this._ilogger.LogDebug($"{name} {password} 登陆系统");
    #region 这里应该是要到数据库中查询验证的
    CurrentUser currentUser = new CurrentUser()
    {
        Id = 123,
        Name = "Bingle",
        Account = "Administrator",
        Password = "123456",
        Email = "415473422@qq.com",
        LoginTime = DateTime.Now,
        Role = name.Equals("Bingle") ? "Admin" : "User"
    };
    #endregion

    #region cookie
    {
        ////就很像一个CurrentUser,转成一个claimIdentity
        var claimIdentity = new ClaimsIdentity("Cookie");
        claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, currentUser.Id.ToString()));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Name, currentUser.Name));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Email, currentUser.Email));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Role, currentUser.Role));
        claimIdentity.AddClaim(new Claim(ClaimTypes.Sid, currentUser.Id.ToString()));
        var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
        base.HttpContext.SignInAsync(claimsPrincipal).Wait();//不就是写到cookie
    }
    #endregion

    return View();
}

再次进行登录,我们就可以看到这样一个Cookie

 

 在这之后,我们再

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇c# sharepoint client object mod.. 下一篇.Net Core权限认证基于Cookie的认..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目