Asp.Net Core - simplest possible forms authentication

前端 未结 2 1483
闹比i
闹比i 2020-12-24 01:38

I have this old MVC5 application that uses forms authentication in the simplest possible form. There is only one account stored in web.config, there are no roles etc.

<
相关标签:
2条回答
  • 2020-12-24 02:30

    To add to Anuraj's answer - a number of classes have been deprecated for .Net Core 2. FYI:

    Startup.cs - In ConfigureServices:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(o => o.LoginPath = new PathString("/account/login"));
    

    Startup.cs - In Configure:

    app.UseAuthentication();
    

    In your account/login controller method/wherever you're doing your authentication:

    var claims = new[] { new Claim(ClaimTypes.Name, "MyUserNameOrID"),
        new Claim(ClaimTypes.Role, "SomeRoleName") };
    
    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    await context.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme, 
        new ClaimsPrincipal(identity));
    // Do your redirect here
    

    Sources: https://github.com/aspnet/Announcements/issues/232

    https://github.com/aspnet/Security/issues/1310

    0 讨论(0)
  • 2020-12-24 02:31

    It is not that simple :)

    1. In the Startup.cs, configure method.

      app.UseCookieAuthentication(options =>
      {
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.LoginPath = "/Home/Login";
      });
      
    2. Add Authorize attribute to protect the resources you want to secure.

      [Authorize]
      public IActionResult Index()
      {
        return View();
      }
      
    3. In the Home Controller, Login Post action method, write the following method.

      var username = Configuration["username"];
      var password = Configuration["password"];
      if (authUser.Username == username && authUser.Password == password)
      {
        var identity = new ClaimsIdentity(claims, 
            CookieAuthenticationDefaults.AuthenticationScheme);
      
        HttpContext.Authentication.SignInAsync(
          CookieAuthenticationDefaults.AuthenticationScheme,
          new ClaimsPrincipal(identity));
      
        return Redirect("~/Home/Index");
      }
      else
      {
        ModelState.AddModelError("","Login failed. Please check Username and/or password");
      }
      

    Here is the github repo for your reference : https://github.com/anuraj/CookieAuthMVCSample

    0 讨论(0)
提交回复
热议问题