- 在startup中添加授权相关的管道
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace mvcforcookie { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication.Cookies; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option => option.LoginPath = "/Acounnt/Index"); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
- 将需要权限访问的页面贴上特性标签
[Authorize(Roles="Admin")] 表名只有Admin身份的人才能进入Admin控制器
- 用户成功输入用户名和密码之后生成用户票据
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using mvcforcookie.Models; namespace mvcforcookie.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; using System.Security.Claims; public class AcounntController : Controller { public IActionResult Index() { //数据库查询用户输入的用户名和密码等一系列匹配操作 //模拟用户登录后的操作 //创建一个用户身份 var claims=new List<Claim>{ new Claim(ClaimTypes.Name,"cyao"), new Claim(ClaimTypes.Role,"Admin") }; var claimidentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme); //向上下文容器中添加当前用户 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimidentity)); return Ok(); } public IActionResult LoginOut() { HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } } }
-
如果要获取当前用户的身份和用户名的话
ViewBag.User= User.Claims.Where(c =>c.Type==ClaimTypes.Name).First().Value; ViewBag.Type= User.Claims.Where(c =>c.Type==ClaimTypes.Role).First().Value;