zoukankan      html  css  js  c++  java
  • 把旧系统迁移到.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

  • 相关阅读:
    《移动开发者周刊》第十一期
    2012安卓巴士开发者沙龙成都站大家抓紧报名
    23岁那年你正处在哪个状态?现在呢?
    《老罗Android开发视频教程》老罗来交国庆的答卷了
    程序员,你的一千万在哪里?
    《老罗Android开发视频教程》更新
    2012全球开发者大会项目投资一对一相亲会
    windows远程桌面
    [LeetCode] NQueens
    [LeetCode] Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/zitjubiz/p/net_core_daily_11_claims_Identity.html
Copyright © 2011-2022 走看看