欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Net Core 2.0 登陆功能 Cookie(学习)

程序员文章站 2022-03-29 12:51:20
AdminController中添加引用: Index添加[Authorize]权限要求: StartUp.cs中添加引用: StartUp.cs ConfigureServices中添加常量: 添加中间件: 此时,访问Admin页面,自动跳转至Account/Login?ReturnUrl=%2F ......

AdminController中添加引用:

using Microsoft.AspNetCore.Authorization;

Index添加[Authorize]权限要求:

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

 StartUp.cs中添加引用:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

StartUp.cs ConfigureServices中添加常量:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddMvc(); }

添加中间件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
}

此时,访问Admin页面,自动跳转至Account/Login?ReturnUrl=%2FAdmin

添加AccountController.cs控制器,编写MakeLogin和Logout。此时访问Account/MakeLogin后,访问Admin能正常访问。

public class AccountController : Controller
    {
        public IActionResult MakeLogin()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,"liumuu"),
                new Claim(ClaimTypes.Role,"admin")
            };
            var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity));
            return Ok();
        }

        public IActionResult Logout()
        {
            HttpContext.SignOutAsync();
            return Ok();
        }
    }

 可自定义默认选项:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
         options.LoginPath = "/Account/Login";
    });
services.AddMvc(); }

 新建ViewModel:

public class RegisterViewModel
    {
        public string Email { get; set; }

        public string Password { get; set; }

        public string ConfirmPassword { get; set; }
    }
public class LoginViewModel
    {
        [Required]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
@model RegisterViewModel

@{
    ViewData["Title"] = "Register";
}

<h2>Register</h2>

<div class="row">
    <div class="col-md-4">
        <form method="post">
            <h4>Create Account</h4>
            <hr />
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" type="password" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="ConfirmPassword"></label>
                <input asp-for="ConfirmPassword" type="password" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default btn-sm">Regtister</button>
        </form>
    </div>
</div>
@model LoginViewModel

@{
    ViewData["Title"] = "Login";
}

<h2>Login</h2>

<div class="row">
    <div class="col-md-4">
        <form method="post">
            <h4>Use a Account to Login</h4>
            <hr />
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" class="form-control" />
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-default btn-sm">Login</button>
            </div>
        </form>
    </div>
</div>

 创建Models:ApplicationUser.cs和ApplicationRole.cs:

public class ApplicationUser : IdentityUser<int>
    {

    }
public class ApplicationRole : IdentityRole<int>
    {

    }

数据连接:ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }
    }

appsettings.json中添加数据链接:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "GetConnectionString": {
    "Default": "Data Source  = .; Database = database; User ID = sa; Password = 123"
  }
}

StartUp.cs中添加数据引用、密码设置等:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("Default"));
            });

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Account/Login";
                });

            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireLowercase = false;
            });

            services.AddMvc();
        }

 编辑AccountController.cs:

private UserManager<ApplicationUser> _userManager;
private SignInManager<ApplicationUser> _signInManager;

public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
      _userManager = userManager;
      _signInManager = signInManager;
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
    {
        var identityUser = new ApplicationUser
        {
            Email = registerViewModel.Email,
            UserName = registerViewModel.Email,
            NormalizedUserName = registerViewModel.Email
        };

        var identityResult = await _userManager.CreateAsync(identityUser, registerViewModel.Password);

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

        return View();
}