Install
https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer
| using Microsoft.AspNetCore.Authentication.JwtBearer; | |
| using Microsoft.AspNetCore.Authorization; | |
| [ApiController] | |
| [Route("[controller]")] | |
| 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] | |
| [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] | |
| 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(); | |
| } | |
| } |
| using Microsoft.AspNetCore.Authentication.JwtBearer; | |
| public class Startup | |
| { | |
| // This method gets called by the runtime. Use this method to add services to the container. | |
| public void ConfigureServices(IServiceCollection services) | |
| { | |
| services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(); | |
| //... | |
| } | |
| // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
| public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
| { | |
| //... | |
| app.UseAuthentication(); | |
| app.UseAuthorization(); | |
| //... | |
| } | |
| } |