Asp.Net Core登陆授权及身份认证
2018-06-12 18:28
615 查看
Asp.Net Core依然借助于 Microsoft.AspNetCore.Authentication的认证组件。
首先在启动类Start中,添加入下代码:
主要是添加认证和Cookie服务。
其次,配置中间件:
登陆页面处理:
通过调用HttpContext的SignInAsync方法,实现登陆授权。这里需要注意的是保证前后AuthenticationType类型一致。
首先在启动类Start中,添加入下代码:
/// <summary> /// /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.Cookie.Name = "_AdminTicketCookie"; o.LoginPath = new PathString("/Account/Login"); o.LogoutPath = new PathString("/Account/Login"); o.AccessDeniedPath = new PathString("/Error/Forbidden"); }); services.AddTransient<TiKu.Application.Interfaces.IAdminService, TiKu.Application.AdminService>(); services.AddMvc(); }
主要是添加认证和Cookie服务。
其次,配置中间件:
app.UseAuthentication();//添加授权中间件 必须卸载app.UseMvc();之前。
登陆页面处理:
/// <summary> /// <![CDATA[登陆]]> /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public async Task<ActionResult> Login(Models.LoginViewModel model) { //模型验证通过后 if (ModelState.IsValid) { TiKu.Domain.Entity.tb_Admin admin = null; //验证用户名密码 if (_AdminService.CheckAccountAndPassword(account: model.account, password: model.password, admin: out admin)) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);//一定要声明AuthenticationScheme identity.AddClaim(new Claim(ClaimTypes.Name, admin.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Sid, model.account)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.account)); await HttpContext.SignInAsync(identity.AuthenticationType, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, RedirectUri = "/Home/Index", }); } else { await HttpContext.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme); ModelState.AddModelError("", "用户名或密码错误!"); } } return View(model); }
通过调用HttpContext的SignInAsync方法,实现登陆授权。这里需要注意的是保证前后AuthenticationType类型一致。
相关文章推荐
- ASP.NET CORE系列【四】基于Claim登录授权
- ASP.NET Core 认证与授权[3]:OAuth & OpenID Connect认证
- ASP.NET Core 认证与授权[4]:JwtBearer认证
- ASP.NET Core 认证与授权[4]:JwtBearer认证
- ASP.NET Core 认证与授权[6]:授权策略是怎么执行的?
- asp.net core策略授权
- 如何在ASP.NET Core中实现一个基础的身份认证
- 【译】在Asp.Net Core 中使用外部登陆(google、微博...)
- ASP.NET Core 认证与授权[2]:Cookie认证
- 【转载】asp.net core 2.0的认证和授权
- 【ASP.NET Core】运行原理(4):授权
- 菜鸟入门【ASP.NET Core】14:MVC开发:UI、 EF + Identity实现、注册实现、登陆实现
- ASP.NET Core 认证与授权[6]:授权策略是怎么执行的?
- asp.net core策略授权
- 【ASP.NET Core快速入门】(十四)MVC开发:UI、 EF + Identity实现、注册实现、登陆实现
- ASP.NET Core 认证与授权[5]:初识授权
- ASP.NET Core 认证与授权[5]:初识授权
- asp.net core的认证和授权
- ASP.NET Core 认证与授权[7]:动态授权
- asp.net core策略授权