设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-11-22 17:20 所属栏目:128 来源:网络整理
导读:public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//默认授权机制 .AddJwtBearer(options = { opti

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

到此这篇关于ASP.NET Core使用JWT认证授权的方法的文章就介绍到这了,更多相关ASP.NET Core JWT认证授权 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读