Asp.net core web API 应用JWT验证

1、新建Asp.net core web Api 应用程序

Asp.net core web API 应用JWT验证_第1张图片

2、目录结构

Asp.net core web API 应用JWT验证_第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.cs

[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 _logger;

        public WeatherForecastController(ILogger logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable 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 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(Configuration.GetSection("jwtConfig"));
            JwtTokenField jwtTokenField = Configuration.GetSection("jwtConfig").Get();
            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();


        }

        // 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、启动运行

Asp.net core web API 应用JWT验证_第3张图片

14、使用Postman访问APi资源

Asp.net core web API 应用JWT验证_第4张图片

你可能感兴趣的:(core,Asp.net,core,Api,Jwt)