1、新建Asp.net core web Api 应用程序
2、目录结构
3、Nuget包下载安装
Microsoft.AspNetCore.Authentication.JwtBearer
Newtonsoft.Json
4、修改launchSettings.json
{ "profiles": { "WebApplication2": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "launchUrl": "swagger", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
5、WeatherForecastController
[ApiController] [Route("[controller]")] [Authorize] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } }
6、修改appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "jwtConfig": { "secret": "qwertyuiop1234354654", "issuer": "MyJwtTest", "audience": "MyTest", "accessExpiration": 60, "refreshExpiration": 90 }, "AllowedHosts": "*" }
7、添加JwtTokenField.cs
public class JwtTokenField { [JsonProperty("secret")] public string Secret { get; set; } [JsonProperty("issuer")] public string Issuer { get; set; } [JsonProperty("audience")] public string Audience { get; set; } [JsonProperty("accessExpiration")] public int AccessExpiration { get; set; } [JsonProperty("refreshExpiration")] public int RefreshExpiration { get; set; } }
8、添加RequestUser.cs
public class RequestUser { public string Name { get; set; } public string Password { get; set; } }
9、添加IAuthorizeService.cs
public interface IAuthorizeService { bool IsAuthenticated(RequestUser request ,out string token); }
10、添加AuthorizeService.cs
public class AuthorizeService : IAuthorizeService { private readonly JwtTokenField _jwtTokenField; public AuthorizeService(IOptions<JwtTokenField> jwtToken) { _jwtTokenField = jwtToken.Value; } public bool IsAuthenticated(RequestUser request, out string token) { var claims = new[] { new Claim(ClaimTypes.Name,request.Name) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenField.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken(_jwtTokenField.Issuer, _jwtTokenField.Audience, expires: DateTime.Now.AddMinutes(_jwtTokenField.AccessExpiration), signingCredentials: credentials); token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return true; } }
11、修改Startup.cs
public class Startup { private readonly string JwtScheme = "MyJwtScheme"; 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.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication2", Version = "v1" }); }); services.Configure<JwtTokenField>(Configuration.GetSection("jwtConfig")); JwtTokenField jwtTokenField = Configuration.GetSection("jwtConfig").Get<JwtTokenField>(); services.AddAuthentication(_ => { _.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; _.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; } ).AddJwtBearer(_ => { _.RequireHttpsMetadata = false; _.SaveToken = true; _.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenField.Secret)), ValidIssuer = jwtTokenField.Issuer, ValidAudience = jwtTokenField.Audience, ValidateIssuer = false, ValidateAudience = false, }; } ); services.AddScoped<IAuthorizeService, AuthorizeService>(); } // 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", "WebApplication2 v1")); } app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
12、添加AuthenticationController.cs
[Route("api/[controller]/[action]")] [ApiController] [Authorize] public class AuthenticationController : ControllerBase { private readonly IAuthorizeService _authService; public AuthenticationController(IAuthorizeService authService) { _authService = authService; } [AllowAnonymous] //[HttpPost,Route("requestToken")] [HttpPost] public ActionResult RequestToken([FromBody] RequestUser request) { string token; if (_authService.IsAuthenticated(request, out token)) { return Ok(token); } return BadRequest("Invalid Request"); } [HttpGet] public ActionResult Get() { return BadRequest("Invalid Get"); } }
备注:[AllowAnonymous]特性添加后,Action不会被验证
13、启动运行
14、使用Postman访问APi资源