zoukankan      html  css  js  c++  java
  • asp.net core2 mvc 基础教程--ASP.NET Core Identity 入门

    ASP.NET Core Identity

    • 身份认证和授权系统
    • 成员管理
    • 默认使用 MSSQL
    • 支持外部的 Provider

    ASP.NET Core Identity 重点类

    • UserManager<IdentityUser>:用户管理
    • SignInManager<IdentityUser>:身份认证

     

     

    public void ConfigureServices(IServiceCollection services)
    
    {
    
        ...
    
        // 注册 IdentityDbContext
    
        services.AddDbContext<IdentityDbContext>(options =>
    
            options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
    
                b => b.MigrationsAssembly("Tutorial.Web")));
    
    
        // 注册 Identity 服务
    
        services.AddDefaultIdentity<IdentityUser>()
    
            .AddEntityFrameworkStores<IdentityDbContext>();
    
    
        // 配置 Identity
    
        services.Configure<IdentityOptions>(options =>
    
        {
    
            // Password settings.
    
            options.Password.RequireDigit = false; //需要数值
    
            options.Password.RequireLowercase = false;//需要小写字母
    
            options.Password.RequireNonAlphanumeric = false;//需要非数值类型
    
             options.Password.RequireUppercase = true; // 需要大写
    options.Password.RequiredLength = 6; //长度
    options.Password.RequiredUniqueChars = 1;//唯一字符
    }); }
    public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger) { ... app.UseAuthentication(); app.UseMvc(builder => { builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); }); }

    注册:

    [HttpPost]
    public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
    {
    
        if (ModelState.IsValid)
        {
            var user = new IdentityUser
            {
                UserName = registerViewModel.UserName
            };
    
    
            var result = await _userManager.CreateAsync(user, registerViewModel.PassWord);
            if (result.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }
            return View(registerViewModel);
        }
    
        return View(registerViewModel);
    }

    通过 Authorize 特性,限定只有登录用户才能添加学生:

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

    更多用法请参考https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio

  • 相关阅读:
    05.迪米特原则 (LOD)
    04.接口隔离原则 (ISP)
    03.依赖倒置原则 (DIP)
    02.里氏替换原则 (LSP)
    01.单一职责原则 (SRP)
    Flutter点击事件的穿透,父元素点击事件覆盖了子元素点击的问题
    flutter dart语法判断 0/0==Nan 1/0==Infinity的问题
    vue项目引入三方字体
    vue echart图表打包后 图片不显示
    vue设置页面的高度100%
  • 原文地址:https://www.cnblogs.com/cqqinjie/p/13203116.html
Copyright © 2011-2022 走看看