Asp.Net Core 2.0 登陆功能 Cookies

发布日期:2018-02-22    浏览次数:726

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();
}

 

本文网址:https://www.wyxxw.cn/blog-detail-2-21-367.html

返回列表

非特殊说明,本文版权归原作者所有,转载请注明出处

提示:本站所有资源仅供学习与参考,请勿用于商业用途。图片来自互联网~如侵犯您的权益,请联系QQ:1067507709.

提示:转载请注明来自:https://www.cnblogs.com/liumuu/p/8286581.html 。 转载人:momo