ASP.NET Core使用JWT认证授权的方法(2)

using JWTS.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace JWTS.Controllers { [Route("api/[controller]")] [ApiController] public class AuthenticationController : ControllerBase { #region 构造函数 private ILogger<AuthenticationController> _logger; private IJWTService _iJWTService; private readonly IConfiguration _iConfiguration; public AuthenticationController(ILogger<AuthenticationController> logger, IConfiguration configuration , IJWTService service) { _logger = logger; _iConfiguration = configuration; _iJWTService = service; } #endregion /// <summary> /// 实际场景使用Post方法 /// :5000/api/Authentication/Login?name=william&password=123123 /// </summary> /// <param></param> /// <param></param> /// <returns></returns> [Route("Login")] [HttpGet] public IActionResult Login(string name, string password) { //这里应该是需要去连接数据库做数据校验,为了方便所有用户名和密码写死了 if ("william".Equals(name) && "123123".Equals(password))//应该数据库 { var role = "Administrator";//可以从数据库获取角色 string token = this._iJWTService.GetToken(name, role); return new JsonResult(new { result = true, token }); } return Unauthorized("Not Register!!!"); } } }

2、资源中心API:使用从认证服务中心获取的Token,去访问资源,资源中心对用户信息以及Token进行鉴权操作,认证失败返回401

1、资源中心添加Nuget包(Microsoft.AspNetCore.Authentication.JwtBearer)

2、添加Authentication服务,添加JwtBearer,通过Configuration获取TokenParameter对象

using System; using System.Text; using API.Core.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; namespace API.Core { public class Startup { private TokenParameter _tokenParameter; public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; _tokenParameter = configuration.GetSection("TokenParameter").Get<TokenParameter>()??throw new ArgumentNullException(nameof(_tokenParameter)); } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//默认授权机制 .AddJwtBearer(options => { options.TokenValidationParameters=new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = _tokenParameter.Issuer, ValidAudience = _tokenParameter.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.SecurityKey)) }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }

3、在资源控制器上添加[Authorize]属性,以启用认证授权访问API资源

   [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(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/41f2138b562466263ea47740f45cb275.html