ASP.NET Core Web API 5.0 JWT身份验证(JSON BASE TOKEN)
介绍
身份验证在确保组织的数据/网络等安全方面起着非常重要的作用。市场上有许多身份验证方法,但最流行的方法是“基于令牌的身份验证”。
在本文中,我们将讨论并使用 Asp.net Core Web API 5.0 + JWT(JSON Web Token)实现基于令牌的身份验证。
我们将创建一个简单的 Web API 来理解 JWT。完成后,我们可以使用 postman 或 swagger 来测试我们的 Web API。
如果您不了解 JWT,我建议您先阅读本文,然后再回来。
什么是基于令牌的认证?
在开始之前,我们应该知道什么是身份验证。
简而言之,身份验证是使用凭据或身份验证用户。
现在想到的下一个问题是“Web API 中基于令牌的身份验证是什么”?
令牌基础认证过程,
- 客户端使用凭据向服务器发送请求。
- 服务器验证凭据并创建访问令牌并将其发送回客户端。
- 所有子序列都请求内容此令牌,直到其过期。
市场上有许多开放标准可以在 Web API 中实现基于令牌的身份验证,其中最流行的是 JSON WEB TOKEN(JWT)。
在 Web API 中创建 JWT 身份验证的步骤
Web API 项目具有以下端点,
- /authenticate – 验证成员凭证并发送子序列请求的访问令牌。
- /All members – 返回成员列表。
- / MemberByid /id – 成员按 id 过滤并返回单个成员。
让我们使用 Visual Studio 2019 创建项目。
第1步
创建一个新项目。
第2步
选择“Asp.Net Core Web API”模板,然后单击“下一步”按钮。
第 3 步
根据上述屏幕配置项目名称、位置。单击下一步按钮。
第四步
提供目标框架 (.Net 5.0) 并单击创建按钮以创建 Web API 项目。
“MemberJWTDemo”项目已成功创建,默认解决方案应如上图所示。
初始项目设置已准备就绪,现在按照以下步骤实施 JWT 身份验证。
第 5 步
从项目中删除默认控制器“WeatherForecastController.cs”和“WeatherForcast.cs”文件。
第 6 步
我们需要在中间件中启用身份验证来验证成员。为此,请打开 Startup.cs 文件并添加以下代码,
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MemberJWTDemo
{
public class Startup
{
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 = "MemberJWTDemo", Version = "v1" });
});
}
// 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", "MemberJWTDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
为了验证成员的凭据并生成 JWT 令牌,我们需要一个自定义的身份验证类。
第 7 步
首先,我们将创建一个名为“IJwtAuth.cs”文件的接口,
namespace MemberJWTDemo
{
public interface IJwtAuth
{
string Authentication(string username, string password);
}
}
第 8 步
现在添加一个名为“Auth”的新类并实现“IAuth”接口。
步骤 9
我们需要为身份验证添加 Nuget 包“Microsoft.AspNetCore.Authentication”。
我们将保留硬编码的用户名和密码以用于演示目的。在实际场景中,它将来自数据库。
如果用户通过身份验证成功,那么我们将创建一个 JWT 令牌。
第 10 步
要创建 JWT 令牌,我们需要安装 Nuget 包“System.IdentityModel.Tokens.Jwt”。
第 11 步
现在我们将在 Auth 类 – 身份验证方法中编写以下代码以在身份验证后创建令牌。
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Security.Claims;
namespace MemberJWTDemo
{
public class Auth : IJwtAuth
{
private readonly string username = "kirtesh";
private readonly string password = "Demo1";
private readonly string key;
public Auth(string key)
{
this.key = key;
}
public string Authentication(string username, string password)
{
if (!(username.Equals(username) || password.Equals(password)))
{
return null;
}
// 1. Create Security Token Handler
var tokenHandler = new JwtSecurityTokenHandler();
// 2. Create Private Key to Encrypted
var tokenKey = Encoding.ASCII.GetBytes(key);
//3. Create JETdescriptor
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(
new Claim[]
{
new Claim(ClaimTypes.Name, username)
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature)
};
//4. Create Token
var token = tokenHandler.CreateToken(tokenDescriptor);
// 5. Return Token from method
return tokenHandler.WriteToken(token);
}
}
}
在上面的代码中,
- 创建安全处理程序 – “token handler”。
- 创建令牌处理程序后,我们将密钥加密为字节。
- 现在我们将创建一个令牌描述符。
- Subject – 新声明标识
- Expired – 何时过期。
- SigningCredential – 私钥 + 算法
- 现在我们将使用令牌处理程序的“create token”方法创建一个令牌。
- 从身份验证方法返回令牌。
现在我们将创建一个控制器并使用authentication 方法。
第 12 步
使用名为 Authentication 的 HTTP POST 端点创建新的控制器“Members”。
第 13 步
在下面的屏幕中单击添加并提供控制器名称,
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace MemberJWTDemo.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class MembersController : ControllerBase
{
private readonly IJwtAuth jwtAuth;
private readonly List<Member> lstMember = new List<Member>()
{
new Member{Id=1, Name="Kirtesh" },
new Member {Id=2, Name="Nitya" },
new Member{Id=3, Name="pankaj"}
};
public MembersController(IJwtAuth jwtAuth)
{
this.jwtAuth = jwtAuth;
}
// GET: api/<MembersController>
[HttpGet]
public IEnumerable<Member> AllMembers()
{
return lstMember;
}
// GET api/<MembersController>/5
[HttpGet("{id}")]
public Member MemberByid(int id)
{
return lstMember.Find(x => x.Id == id);
}
[AllowAnonymous]
// POST api/<MembersController>
[HttpPost("authentication")]
public IActionResult Authentication([FromBody]UserCredential userCredential)
{
var token = jwtAuth.Authentication(userCredential.UserName, userCredential.Password);
if (token == null)
return Unauthorized();
return Ok(token);
}
}
}
在上面的代码中,
- 身份验证方法从正文中获取用户名和密码。
- 将凭证传递给 jwtAuth。获取令牌的身份验证方法。
- 返回令牌。
- 添加属性 [AllowAnonymous],因为此方法可由任何用户处理。
- 将 [Authorize] 属性添加到成员控制器。
- 在构造函数中添加“jwtAuth”。
第 14 步
创建 UserCredential 类,如下所示,
namespace MemberJWTDemo.Controllers
{
public class UserCredential
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
第 15 步
创建Member model类如下,
namespace MemberJWTDemo
{
public class Member
{
public int Id { get; set; }
public string Name { get; set; }
}
}
我们需要在 Startup.cs 文件中添加依赖项。此外,我们将添加 JETBearar 来解密密钥。
第 16 步
安装“Microsoft.AspNetCore.Authentication.JwtBearer”NuGet 包。
第 17 步
在 startup.cs 文件中添加以下代码,
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;
using Microsoft.OpenApi.Models;
using System.Text;
namespace MemberJWTDemo
{
public class Startup
{
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();
var key = "This is my first Test Key";
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key))
};
});
services.AddSingleton<IJwtAuth>(new Auth(key));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MemberJWTDemo", Version = "v1" });
})
}
// 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", "MemberJWTDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
我们完成了代码。
第 18 步
现在我们将使用 Postman 或 swagger 等调用 API 端点。
第 19 步
首先,我们将调用post方法/API/Members/authentication,
令牌创建成功。现在在子序列请求中,我们必须在标头中传递这个token (Key – authorized,和value -token)
我希望你喜欢这篇文章并觉得它很有用。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!