• 把旧系统迁移到.Net Core 2.0 日记(11) -- Authentication 认证 claimsIdentity 对比 之前的FormAuthentication


    实现最简单的认证,类似之前的FormAuthentication

    在 Startup 的 ConfigureServices() 方法中添加 Authentication 的配置: 这个CookieAuthenticationDefaults类默认的登录地址是/Account/Login,如果要要修改

    则可以在后面的AddCookie()方法里修改路径

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie();

    在 Startup 的 Configure() 方法

    app.UseAuthentication();

    AccountController方法

       public class AccountController : Controller
        {
            private readonly CRMContext _context;
            public AccountController(CRMContext context)
            {
                _context = context;
            }
            [AllowAnonymous]
            [HttpGet]
            public IActionResult Login()
            {
                return View();
            }
            public async Task<IActionResult> Logout()
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                return RedirectToAction("Login");
            }
            [AllowAnonymous]
            [HttpPost]
            public async Task<IActionResult> Login(IFormCollection form)
            {
                string userName = form["txtLoginId"];
                string pwd = form["txtPwd"];
                if (0 == new UserLogic(_context).UserLogin(userName, pwd))
                {
                    var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userName) }, "Basic");
                    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
                    return Json(new { isSuccess = true, message = "登录成功" });
                }
                else
                {
                    return Json(new { isSuccess = false, message = "登录失败" });
                }
    
    
            }

    我们之前只能把登录的用户名放在FormAuthentication的cookie里, 使用时就用User.Identity.Name获得当前登录的用户名,

    但是现在我们可以把其他的信息,如UserId,SystemId都放到ClaimsIdentity里. 这样写

    var claimsIdentity = new ClaimsIdentity(new Claim[] 
                    { 
                        new Claim(ClaimTypes.Name, userName),
                        new Claim(ClaimTypes.Sid, "1"),
                        new Claim(ClaimTypes.System,"HR")
                    }, "Basic");
    
    //使用方法
    //User.Claims.FirstOrDefault(t => t.Type == System.Security.Claims.ClaimTypes.Sid).Value
    //User.Claims.FirstOrDefault(t => t.Type == System.Security.Claims.ClaimTypes.System).Value

    登录提交Form的参数, 要改成IFormCollection,否则会出错

    The 'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinder' cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'.

    Change the model type to 'Microsoft.AspNetCore.Http.IFormCollection' instead.

    System.Security.Cryptography.HashAlgorithm.Create(string hashName) Hash方法还没实现,会出现错误

    PlatformNotSupportedException: Operation is not supported on this platform.

    解决方法, 要添加nuget包

    https://stackoverflow.com/questions/35363358/computing-sha1-with-asp-net-core

    这样写

    var sha1 = System.Security.Cryptography.SHA1.Create();

     

    参考文章:

    https://www.cnblogs.com/seriawei/p/7452743.html

    http://www.cnblogs.com/dudu/p/7631927.html

    http://www.cnblogs.com/dudu/p/6368240.html

    http://www.cnblogs.com/bidianqing/p/6870163.html

    http://www.cnblogs.com/tdfblog/p/aspnet-core-security-authentication-cookie.html

    http://www.cnblogs.com/RainingNight/p/introduce-basic-authentication-in-asp-net-core.html

  • 相关阅读:
    Java中ArrayList与LinkedList的区别
    Java中String、StringBuffer、StringBuilder的区别
    Java中的String类能否被继承?为什么?
    JAVA有哪些数据类型?基本数据类型各占多少个字节
    Linux远程复制命令SCP
    CentOS添加用户并加入sudo权限
    nginx配置反向代理解决前后端分离跨域问题
    执行ssh-add时出现Could not open a connection to your authentication agent
    Git 修改源地址
    ssh配置git clone简易流程
  • 原文地址:https://www.cnblogs.com/zitjubiz/p/net_core_daily_11_claims_Identity.html
Copyright © 2020-2023  润新知