博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Asp.Net Core 2.0 登陆功能 Cookies(学习)
阅读量:5272 次
发布时间:2019-06-14

本文共 5533 字,大约阅读时间需要 18 分钟。

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
{ 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";}

Register

Create Account


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

Login

Use a Account to Login


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

public class ApplicationUser : IdentityUser
{ }
public class ApplicationRole : IdentityRole
{ }

数据连接:ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext
{ public ApplicationDbContext(DbContextOptions
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
(options => { options.UseSqlServer(Configuration.GetConnectionString("Default")); }); services.AddIdentity
() .AddEntityFrameworkStores
() .AddDefaultTokenProviders(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; }); services.Configure
(options => { options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; }); services.AddMvc(); }

 编辑AccountController.cs:

private UserManager
_userManager;private SignInManager
_signInManager;public AccountController(UserManager
userManager, SignInManager
signInManager){ _userManager = userManager; _signInManager = signInManager;}
[HttpPost]public async Task
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.cnblogs.com/liumuu/p/8286581.html

你可能感兴趣的文章
solt插槽的使用。
查看>>
js学习总结
查看>>
log4j与log4j.properties的配置
查看>>
使用pageHelper遇到的问题
查看>>
WORD 内码转汉字
查看>>
check tcl version
查看>>
1089 狼人杀-简单版 (20 分)
查看>>
Https如何确保传输安全的
查看>>
CSS3 3D Transform
查看>>
js深拷贝
查看>>
http和socket之长连接和短连接区别(转)
查看>>
【HTML】网页中如何让DIV在网页滚动到特定位置时出现
查看>>
文件序列化
查看>>
C++11 中的线程、锁和条件变量
查看>>
HDU 2485 Destroying the bus stations(!最大流∩!费用流∩搜索)
查看>>
Oracle关于用户信息的一些SQL语句
查看>>
2019-02-28处理公司同事无法上网事件记录
查看>>
cookie的过期时间
查看>>
HTCVive使用
查看>>
Javascript 浏览器检测
查看>>