1、新建Asp.net Core Web Mvc项目
2、项目目录结构如下:
3、修改launchSettings.json
{ "profiles": { "WebApplication3": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
4、Nuget包下载安装
Microsoft.AspNetCore.Authentication.JwtBearer
5、添加JwtManage.cs
public class JwtManage { public static string CreateToken(string name) { var secretKey = "qwertyuiop123456"; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.Name,name), new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( "myToken", "aaaa", claims, expires: DateTime.Now.AddMinutes(90), signingCredentials:credentials ); return new JwtSecurityTokenHandler().WriteToken(token); } }
6、添加UserController.cs
public class UserController : Controller { public IActionResult Index() { return View(); } [HttpPost] public IActionResult Login() { var userName = Request.Form["Name"]; var password = Request.Form["Password"]; if (userName == "admin" && password =="admin") { var token = JwtManage.CreateToken(userName); Response.Cookies.Append("access_token", token); return RedirectToAction("Index", "Home"); } else { return RedirectToAction("Error", "Home"); } } }
7、修改Startup.cs
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.AddControllersWithViews(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Events = new JwtBearerEvents() { OnMessageReceived=context=> { context.Token = context.Request.Cookies["access_token"]; return Task.CompletedTask; } }; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "myToken", ValidAudience = "aaaa", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("qwertyuiop123456")) }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=User}/{action=Index}/{id?}"); }); } }
8、修改HomeController.cs
[Authorize] public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }
9、Views文件下添加User文件夹并添加index.cshtml
@{ ViewData["Title"] = "Login Page"; } <form asp-controller="user" asp-action="login" method="post"> <input type="text" name="name" value=""/> <input type="password" name="password" value=""/> <input type="submit" name="登录" value="登录"/> </form>
10、启动运行,输入admin,admin