• 使用HttpContext.SignInAsync实现简单的授权


    1.  将认证添加到服务中

    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    //登入地址
                    options.LoginPath = "/Account/FcbLogin/";
                    //登出地址
                    options.LogoutPath = "/Account/FcbLogout/";
                    //设置cookie过期时长
                    //options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
                });

    所有CookieAuthenticationOptions 属性可以查看微软官方文档

     

     

    2. 注入管道

    这里认证要在授权之前注入

    app.UseAuthentication();
    

    3. 添加登入和登出

    这里我没有验证用户账号密码,只是写了登入和登出的相关代码,这里也可以喝注入认证那里一样,这是票证过期时间

            [HttpPost]
            public async Task<ActionResult> Login(UserLogin model)
            {
                //这里的scheme一定要和注入服务的scheme一样
                var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
                //自定义的claim信息
                identity.AddClaim(new Claim("abc", "123"));
                AuthenticationProperties properties = new AuthenticationProperties()
                {
                    //设置cookie票证的过期时间
                    ExpiresUtc = DateTime.Now.AddDays(1),
                    RedirectUri = model.ReturnUrl
                };
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);
    
                if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return LocalRedirect("/");
                }
                return LocalRedirect(model.ReturnUrl);
            }
    

      

            [HttpGet]
            public ActionResult FcbLoginOut()
            {
                //AuthenticationProperties properties = new AuthenticationProperties()
                //{
                //    ExpiresUtc = DateTime.Now.AddDays(-100)
                //};
                HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                return Ok();
            }
    

      

  • 相关阅读:
    html+css学习笔记 5[表格、表单]
    html+css学习笔记 4[定位]
    WebService基于SoapHeader实现安全认证
    jquery获取url参数
    邮件群发
    .NET指定程序集的位置
    C# 只启动一个实例完全解决方案
    利用Google API生成二维码
    redis 面试题
    python 操作 redis 集群
  • 原文地址:https://www.cnblogs.com/roubaozidd/p/15715092.html
Copyright © 2020-2023  润新知