Asp.Net Core Identity

1.特点:

1)身份认证和授权系统

2)成员管理

3)默认使用MSSQL

4)支持外部的Provider

 

2.Asp.Net Core Identity重点类

1)SignInManager

2)UserManager

 

3.使用

1)结构:

①控制器:AccountController.cs

②模型:LoginViewModel.cs、RegisterViewModel.cs

③页面:Login.cshtml、Register.cshtml

④生成配置:Startup.cs

Asp.Net Core Identity_第1张图片

 

2)代码:

①AccountController.cs

 

使用: SignInManager和UserManager

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreTest.Web.ViewModel;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace CoreTest.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager _signInManager;
        private readonly UserManager _userManager;


        public AccountController(SignInManager signInManager,
            UserManager userManager)
        {
            _signInManager = signInManager;
            _userManager = userManager;
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        /// 
        /// 登录
        /// 
        /// 
        /// 
        [HttpPost]
        public async Task Login(LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return View(login);
            }

            //通过用户名获取用户信息
            var user = await _userManager.FindByNameAsync(login.UserName);

            //验证密码
            if (user != null)
            {
                var result = await _signInManager
                    .PasswordSignInAsync(user,login.Password,false,false);

                if (result.Succeeded)
                {
                    return RedirectToAction("Index","Home");
                }
            }

            ModelState.AddModelError("","用户名/密码不正确!");

            return View(login);
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }

        /// 
        /// 注册
        /// 
        /// 
        /// 
        [HttpPost]
        public async Task Register(RegisterViewModel register)
        {
            if (ModelState.IsValid)
            {
                //创建用户注册
                var user = new IdentityUser
                {
                    UserName = register.UserName
                };

                var result = await _userManager.CreateAsync(user,register.Password);

                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "Home");
                }

            }

            return View(register);
        }

        /// 
        /// 登出
        /// 
        /// 
        [HttpPost]
        public async Task Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }

    }
}

 

②模型:

LoginViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace CoreTest.Web.ViewModel
{
    /// 
    /// 登录
    /// 
    public class LoginViewModel
    {
        /// 
        /// 用户名
        /// 
        [Required]
        [Display(Name = "用户名")]
        public string UserName {get;set;}

        /// 
        /// 密码
        /// 
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密码")]
        public string Password { get; set; }
    }
}

 

RegisterViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace CoreTest.Web.ViewModel
{
    /// 
    /// 注册
    /// 
    public class RegisterViewModel
    {
        /// 
        /// 用户名
        /// 
        [Required]
        [Display(Name = "用户名")]
        public string UserName { get; set; }

        /// 
        /// 密码
        /// 
        [Required]
        [Display(Name = "密码")]
        public string Password { get; set; }
    }
}

 

③页面:

Login.cshtml

@model LoginViewModel

请您登录或"Register" asp-controller="Account">注册

"Login" asp-controller="Account" method="post">
for="UserName" /> for="UserName">
for="Password" /> for="Password">
"submit" value="提交" />
"All">

 

Register.cshtml

@model RegisterViewModel

注册

"Register" asp-controller="Account" method="post">
for="UserName" /> for="UserName">
for="Password" /> for="Password">
"submit" value="提交" />
"All">

 

④生成配置:

修改Startup.cs(授权配置:红色部分)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CoreTest.Web.Data;
using CoreTest.Web.Model;
using CoreTest.Web.Service;
using CoreTest.Web.Setting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace CoreTest.Web
{
    public class Startup
    {
        private readonly IConfiguration _configuration;

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;

        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //只有一个实例
            services.AddSingleton();

            //每次一个新的Http请求,产生一个新的实例
            services.AddScoped,InMemoryRepository>();

            //使用数据连接
            services.AddDbContext(options => {
                //获取数据连接
                options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
            });

            //授权注册
            services.AddDefaultIdentity()
                .AddEntityFrameworkStores();

            //授权表生成
            services.AddDbContext(options => 
            options.UseSqlServer(
                _configuration.GetConnectionString("DefaultConnection"),
                b => b.MigrationsAssembly("CoreTest.Web")//作用的程序集
                ));

            //授权密码设定
            services.Configure(options =>
            {
                // Password settings.
                options.Password.RequireDigit = false;
                options.Password.RequireLowercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequiredLength = 1;
                options.Password.RequiredUniqueChars = 1;

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

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

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,IConfiguration configuration, IWelcome welcomeService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler();
            }

            app.UseMvc();
            app.UseStaticFiles();
            //app.UseDefaultFiles();

            app.UseStaticFiles(new StaticFileOptions {
                RequestPath= "/node_modules",
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
            });

            //app.UseMvcWithDefaultRoute();
            //app.UseWelcomePage();

            app.UseAuthentication();

            app.UseMvc(route =>
            {
                route.MapRoute("Default", "{Controller=Home}/{Action=Index}/{id?}");

            });


            //app.Run(async (context) =>
            //{
            //    var hell = configuration["DZW"];
            //    var hell2 = welcomeService.GetMessage();
            //    await context.Response.WriteAsync(hell2);
            //});
        }
    }
}

 

 

3)数据库生成

①打开程序包管理器控制台

②执行  add-migration CoreTest2 生成数据库执行文件语句(注:这个时候会报错,因为项目配置中有两个不同烦人数据库链接--Identity和appsettings.json的数据库链接)

提示:

 

Asp.Net Core Identity_第2张图片

这个时候,我们将指明具体的声称对象,执行:add-migration CoreTest3 -Context IdentityDbContext

Asp.Net Core Identity_第3张图片

 

 ③生成数据库

执行:Update-database -Context IdentityDbContext

Asp.Net Core Identity_第4张图片

 

 

 

4)Layout判断是否登录显示用户名

使用

@using Microsoft.AspNetCore.Identity

@inject SignInManager SignInManager

@using Microsoft.AspNetCore.Identity



@inject SignInManager SignInManager



    "viewport" content="width=device-width" />
    @ViewBag.Title


    @*判断是否登录*@
    @if (SignInManager.IsSignedIn(User))
    {
        
} else { 注册 登录 }

11111

@RenderBody()

@RenderSection("bottom", required: false)

 

 5)使用展示

①登录前:

Asp.Net Core Identity_第5张图片

②登录后:

Asp.Net Core Identity_第6张图片

 

 

③授权验证限制:在对应调用的控制器或页面前面加上[Authorize]

Asp.Net Core Identity_第7张图片

 

 

感谢:杨老师

Asp.Net Core Identity_第8张图片

 

参阅:https://www.bilibili.com/video/av38392956/?p=14

 

转载于:https://www.cnblogs.com/dzw159/p/11009857.html

你可能感兴趣的:(Asp.Net Core Identity)