.net 5 Authorize 与 SignIn 和 SignOut 实现登录与登出
1 创建 .net5 web api 项目
2 修改 Startup.cs 如下
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApplication1_WebApi.Controllers; namespace WebApplication1_WebApi { 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(LoginController.AuthenticationScheme).AddCookie(LoginController.AuthenticationScheme, options => { options.LoginPath = "/Login/NotLogin"; // 未授权的登录地址 options.Cookie.Name = "AuthCookie"; }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1_WebApi", Version = "v1" }); }); } // 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(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1_WebApi v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
3 编写 登录用的接口 LoginController
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace WebApplication1_WebApi.Controllers { [ApiController] [Route("[controller]/[action]")] public class LoginController : ControllerBase { // 登录模式名 public const string AuthenticationScheme = "MyAuthenticationScheme"; /// <summary> /// 未登录的回调地址 /// </summary> /// <returns></returns> [HttpGet] public IActionResult NotLogin() { return new JsonResult(new {code = 0,msg = "NotLogin" }); } /// <summary> /// 登录接口 /// </summary> /// <returns></returns> [HttpGet] public IActionResult SingIn() { var claimsPricipal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "UserName"), }, AuthenticationScheme)); HttpContext.SignInAsync(AuthenticationScheme, claimsPricipal); return new JsonResult(new {code = 0,msg = "SingIn ok" }); } /// <summary> /// 获取登录用户名 /// </summary> /// <returns></returns> [HttpGet] public IActionResult GetLoginUser() { string userName = User.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Name)?.Value; return new JsonResult(new { code = 0, msg = "GetLoginUser ok", data = new{ userName } }); } /// <summary> /// 登出接口 /// </summary> /// <returns></returns> [HttpGet] public IActionResult SingOut() { var claims = User.Claims.ToList(); HttpContext.SignOutAsync(AuthenticationScheme); return new JsonResult(new { code = 0, msg = "SingOut ok" }); } } }
4 编写受保护的 apicontroller
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1_WebApi.Controllers { [Authorize] [ApiController] [Route("[controller]/[action]")] public class ApiController : ControllerBase { /// <summary> /// 需要授权api /// </summary> /// <returns></returns> [HttpGet] public IActionResult AuthorizeApi1() { return new JsonResult(new { code = 0,msg = "AuthorizeApi1 ok" }); } } }
5 测试
项目启动后,先访问 /Api/AuthorizeApi1 ,这时由于未登录会返回返回未登录接口的信息

然后调用登录接口 /Login/SingIn ,成功后再访问 /Api/AuthorizeApi1 接口成功


浙公网安备 33010602011771号