asp.net Identity身份验证 .net core 2.1
创始人
2024-09-16 07:00:51
0

在.NET Core 2.1中,使用ASP.NET Identity进行身份验证的解决方法如下:

  1. 创建一个新的ASP.NET Core 2.1项目。
  2. 在项目文件中添加以下依赖关系:

  
  

  1. 创建一个新的IdentityContext类,继承自IdentityDbContext:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace YourNamespace
{
    public class IdentityContext : IdentityDbContext
    {
        public IdentityContext(DbContextOptions options) : base(options)
        {
        }
    }
}
  1. 在Startup.cs文件中进行配置:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using YourNamespace;

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext(options =>
            options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity()
            .AddEntityFrameworkStores()
            .AddDefaultTokenProviders();

        services.Configure(options =>
        {
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;
        });

        services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";
            options.AccessDeniedPath = "/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication(); // 添加身份验证中间件

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
  1. 创建一个AccountController,用于处理用户登录和注册:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;

public class AccountController : Controller
{
    private readonly UserManager _userManager;
    private readonly SignInManager _signInManager;

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

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

    [HttpPost]
    public async Task Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new IdentityUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }
        }
        return View(model);
    }

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

    [HttpPost]
    public async Task Login(LoginViewModel model, string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return LocalRedirect(returnUrl);
            }
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        }
        return View(model);
    }

    [HttpPost]
    public async Task Logout()
    {
        await _signInManager

相关内容

热门资讯

推荐辅助!九天大厅辅助器,天天... 推荐辅助!九天大厅辅助器,天天贵阳辅助工具(分享一款开挂辅助平台);超受欢迎的天天贵阳辅助工具稳赢小...
科技辅助!广东雀神智能插件需要... 科技辅助!广东雀神智能插件需要付费吗,werplan透视挂(一分钟揭秘开挂辅助神器);无需打开直接搜...
关于开挂!雀姬无限钻石辅助,新... 关于开挂!雀姬无限钻石辅助,新道游app辅助器(透视app开挂辅助神器);超受欢迎的雀姬无限钻石辅助...
教会开挂!新天道辅助脚本,杭州... 教会开挂!新天道辅助脚本,杭州都莱挂(实操分享开挂辅助下载)1、下载安装好新天道辅助脚本,进入游戏主...
曝光辅助!新上游辅助器,蜀山四... 曝光辅助!新上游辅助器,蜀山四川小程序辅助开挂(技术分享开挂辅助神器) 【无需打开直接搜索加薇136...
科技开挂!财神十三章辅助,湖北... 科技开挂!财神十三章辅助,湖北逍遥卡五星辅助(避坑细节开挂辅助软件);无需打开直接搜索薇:13670...
传授辅助!方片十三张脚本,山西... 传授辅助!方片十三张脚本,山西奇迹打锅子辅助(揭秘攻略开挂辅助安装);亲,山西奇迹打锅子辅助这款游戏...
发现辅助!天道联盟辅助软件,四... 发现辅助!天道联盟辅助软件,四川途游辅助软件下载(透视私人局开挂辅助工具) >>您好:软件加薇136...
盘点辅助!随意玩免费辅助器有挂... 盘点辅助!随意玩免费辅助器有挂吗,宝宝浙江游戏免费开挂(一分钟教会你开挂辅助下载);无需打开直接搜索...
传授辅助!九酷众游辅助,开心十... 开心十三张有没有挂是一款专注玩家量身打造的游戏记牌类型软件,在开心十三张有没有挂这款游戏中我们可以记...