授权过滤器

用户在登陆的时候,登录状态通过cookie将账号密码进行保存在客户端,是不安全的。使用授权过滤器可以解决该问题。
在建立控制器后,将下列方法写入控制器。我的控制器名称为HomeController

public IActionResult Login()
        {
            return Content("登录");
        }
        public IActionResult DoLogin()
        {
            return Content("登陆成功");
        }
        public IActionResult Center()
        {
            return Content("用户中心");
        }

这样在浏览器访问各个方法都是没有问题的,而在进入用户中心前,加入授权过滤,如下:

public IActionResult Login()
        {
            return Content("登录");
        }
        public IActionResult DoLogin()
        {

            return Content("登陆成功");
        }
        [Authorize]
        public IActionResult Center()
        {
            return Content("用户中心");
        }

在加入授权过滤器后,就不能直接进入用户中心了。要通过授权过滤器,进入用户中心,需要在Startup.cs的ConfigureService方法中,启动这种服务(名字很长)

 services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, o =>
            {
                o.LoginPath = new PathString("/Home/Login");//未经过授权过滤器,返回到登录页面
            }
                    );

添加服务后,也要启动这个登录验证机制才可以。在Startup.cs的Configure方法中加入以下语句:

app.UseAuthentication();

之后在登录验证和用户中心中,通过下列方式进行授权过滤:

public IActionResult Login()
        {
            return Content("登录");
        }
        public IActionResult DoLogin()
        {
            //不建议在cookie中保存账号密码,在登陆后获取要是token
            //获取传递的token 限定通过Forms表单
            ClaimsIdentity identity = new ClaimsIdentity("Forms");
            string token = "123456";
            string name = "张三";
            //将token,name加入到cookie
            identity.AddClaim(new Claim(ClaimTypes.Sid, token));
            identity.AddClaim(new Claim(ClaimTypes.Name, name));
            //将identity数据进行加密
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
            //通过请求上下文形式保存,指定CookieAuthenticationDefaults.AuthenticationScheme名称
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,claimsPrincipal);




            return Content("登陆成功");
        }
        //指定CookieAuthenticationDefaults.AuthenticationScheme识别
        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public IActionResult Center()
        {
            //获取token和name
            String token = User.FindFirstValue(ClaimTypes.Sid);
            String name = User.FindFirstValue(ClaimTypes.Name);
            return Content("用户中心");
        }

注:此文是我写的第一篇技术分享贴,本人也正在学习过程中,由于学习深度、广度不够,不保证文章内容,注释等完全正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值