• 如何在你的.NET程序集成JWT认证
  • 发布于 2个月前
  • 429 热度
    0 评论
  • 乌龙山
  • 0 粉丝 48 篇博客
  •   
前言
JWT是目前最为流行的接口认证方案之一,有关JWT协议的详细内容,请参考:https://jwt.io/introduction 。今天分享一下如何在.NET程序中在使用JWT,现成代码,即拿即用!


集成JWT
Asp.Net Core中集成JWT认证的方式在网络上随便一搜就能找到一堆,主要有两个步骤:
1.在IOC容器中注入依赖
public void ConfigureServices(IServiceCollection services)
{
    // 添加这一行添加jwt验证:
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,//是否验证Issuer
                ValidateAudience = true,//是否验证Audience
                ValidateLifetime = true,//是否验证失效时间
                ClockSkew = TimeSpan.FromSeconds(30),
                ValidateIssuerSigningKey = true,//是否验证SecurityKey
                ValidAudience = Const.Domain,//Audience
                ValidIssuer = Const.Domain,//Issuer,这两项和前面签发jwt的设置一致
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到SecurityKey
            };
        });

}
2.应用认证中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // 添加这一行 使用认证中间件
    app.UseAuthentication();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
    });
}
3.在Controller
[Route("api/[controller]")]
[ApiController] // 添加这一行
public class MyBaseController : ControllerBase
{

}
4.提供一个认证的接口,用于前端获取token
[AllowAnonymous]
[HttpGet]
public IActionResult Get(string userName, string pwd)
{
    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
            new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
            new Claim(ClaimTypes.Name, userName)
        };
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(
            issuer: Const.Domain,
            audience: Const.Domain,
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds);

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }
    else
    {
        return BadRequest(new { message = "username or password is incorrect." });
    }
}
至此,你的应用已经完成了集成JWT认证。

用户评论