代码如下:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json.Serialization; using Simple_Asp.Net_Core.Data; using Simple_Asp.Net_Core.ServiceProvider; using System; namespace Simple_Asp.Net_Core { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddJWT(); services.AddDbContext<CommanderContext>(options => options.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=123456")); services.AddCORS(); services.AddMvc(); services.AddSwagger(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddScoped<ICommanderRepo, SqlCommanderRepo>(); services.AddControllers().AddNewtonsoftJson(s => { s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); } // 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", "ApiHelp V1"); }); } app.UseCors("CorsTest"); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); } } } 接下来就是应用了 首先我们在 CommandsController 控制器上增加特性 [Authorize] 然后启动项目,可以发现,swagger上发出的请求出现了401错误 401的错误就是没有权限HTTP401状态详解 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status/401
现在需要为swagger的请求增加Token 首先增加JWT获取接口,新建控制器OAuthController.cs当前模拟用户信息获取与用户信息校验用户校验
Action增加[AllowAnonymous]特性,让此接口可以接收任何的请求
代码如下:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Simple_Asp.Net_Core.Dtos; using Simple_Asp.Net_Core.Extensions; using Simple_Asp.Net_Core.ServiceProvider; using System; using System.IdentityModel.Tokens.Jwt; using System.Text; namespace Simple_Asp.Net_Core.Controllers { [Route("api/[controller]")] [ApiController] public class OAuthController : ControllerBase { [HttpPost] [AllowAnonymous] public IActionResult Authenticate(string name, string password) { // 此处需补充用户校验与用户具体信息获取... var user = new UserProviderDto(name, password); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(Const.SecurityKey); var tokenDescriptor = new SecurityTokenDescriptor { Audience = Audiences.UpdateAudience(user.Name), Subject = user.GetClaimsIdentity(), Expires = DateTime.UtcNow.AddDays(0.5), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return Ok(new { access_token = tokenString }); } } } 在Dto文件夹下增加用户Dto UserProviderDto.cs代码如下:
namespace Simple_Asp.Net_Core.Dtos { public class UserProviderDto { public UserProviderDto(string name, string password) { Name = name; Password = password; } public string ID { get; set; } /// <summary> /// 用户名 /// </summary> public string Name { get; set; } /// <summary> /// 手机号 /// </summary> public string Phone { get; set; } /// <summary> /// 电子邮箱 /// </summary> public string Mail { get; set; } public string Password { get; set; } } } 新建 Extensions 文件夹 、 新建ClaimLoginUserExtensions 扩展类