Net Core Identity authentication: registration, login and logout (simple example)

I. Introduction

  Generally, we own the system will use a set of their own identity verification authorization code, this time with identity net core to complete a simple registration, login and logout.

Second, the database

  The first is to create a context, I've built a simple and UserClaim Users table, if there is no log-in operation, etc. under UserClaim is being given, it should be related certification of identity.

    public class DataBaseContext : DbContext
    {
        public DataBaseContext(DbContextOptions<DataBaseContext> options)
        : base(options)
        { }
        public DbSet<User> Users { get; set; }
        public DbSet<IdentityUserClaim<string>> UserClaim { get; set; }
    }
    public class User : IdentityUser
    {
        public string companyId { get; set; }
        public string PassWord { get; set; }
    }

  Here User inherited IdentityUser, IdentityUser in to use many of the underlying field, such as UserName, etc. so we can again extend our User class field.

  add-migration Init and then update-database Init Console, generate the table.

Three, Startup Registration Service

  In ConfigureServices registered as follows

  1, connected to the context database

  // add a database connection 
  services.AddDbContext <A DatabaseContext is> (= Options> options.UseSqlServer (Configuration.GetConnectionString ( " DefaultConnection " )));

  2, add a logo, including cookie default UI, and identity tokens to provide experience and adds Entity Framework identity information storage implementation for relational database to create user get user information. AddDefaultIdentity an equivalent AddIdentity, AddDefaultUI AddDefaultTokenProviders and three. If the User does not inherit IdentityUser use AddEntityFrameworkStores error.

  services.AddDefaultIdentity<User>().AddEntityFrameworkStores<DataBaseContext>();

  3, add the Identity option, you can set the strength of the password length, use of character, number of incorrect password and so on.

    services.Configure<IdentityOptions>(options =>
    {
        // password 
        options.Password.RequireDigit = false ;
        options.Password.RequireLowercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = false;
        options.Password.RequiredLength = 1;
        options.Password.RequiredUniqueChars = 1;

        // lock setting 
        options.Lockout.DefaultLockoutTimeSpan TimeSpan.FromMinutes = ( . 5 );
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        // user settings
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = false;
    });

  4, cookie configuration of the application

    services.ConfigureApplicationCookie(options =>
    {
        // Cookie设置
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes ( 5 );

        options.LoginPath = "/Login/Index";
        options.AccessDeniedPath = "/Home/Index";
        options.SlidingExpiration = true;
    });

  Sign up authentication in the Config

  app.UseAuthentication();

Fourth, the simple login, registration and deregistration

  Since it is a simple example, I was really how simple how to code but also no a few.

  Home to create a controller and add [Authorize] characteristics, it is not proven all inaccessible. According to the above Startup.cs UserManager dependency it has been injected, which is used to manage the user registration, such as her.

[Authorize]
    public class HomeController : Controller
    { 
        private UserManager<User> userManager;public HomeController(UserManager<User> _userManager)
        {
            userManager = _userManager;
        }
        public async Task<IActionResult> Index()
        {
            var res = await userManager.GetUserAsync(HttpContext.User);
            return View();
        }
    }

  Then create a Login control, we can write log in on the inside, and methods of cancellation of registration. In addition the controller also UserManager Login injection SignManager, which is used for user login, logout and other operations.

    public class LoginController : Controller
    {
        // for providing persistent storage of user information 
        Private the UserManager <the User> 'userManager';
         Private SignInManager <the User> signManager;
         public the LoginController (the UserManager <the User> _userManager, SignInManager <the User> _signManager)
        {
            userManager = _userManager;
            signManager = _signManager;
        }
    }

  1, Registration

   Register with CreateAsync method, the user is automatically created directly in the database. SignInAsync method for the user to log just registered immediately.

        public async Task<IActionResult> Register()
        {
            var user = new User() { UserName = "xu2", PhoneNumber = "123", companyId = "1" };
            var result = await userManager.CreateAsync(user, "123");
            await signManager.SignInAsync(user, true);
            if (result.Succeeded)
                return Redirect("/Home/Index");
            return Redirect("/Login/Index");
        }

  2, Log

  Login can not be used SignInAsync, and password to use PasswordSignInAsync

        public async Task<IActionResult> Index()
        {
            var s = await signManager.PasswordSignInAsync("xu", "123", true, false);
            return View();
        }

  3, log off

        public async Task<IActionResult> LogOut()
        {
            await signManager.SignOutAsync();
            return View();
        }

  4. Get the current logged-on user

    var res = await userManager.GetUserAsync(HttpContext.User);

 

 

Guess you like

Origin www.cnblogs.com/xwc1996/p/11789052.html