asp.net-core - 如何使用来自 One Api 的一个 jwt 令牌来验证本地企业应用程序 asp.net 核心中的所有 API(不使用 identityserver)
问题描述
我需要为本地应用程序中的所有 api 运行 Api 身份验证服务器(使用 jwt)。如何在不使用身份服务器的情况下创建它?如何在其他 API 上验证初始令牌?如何将接收到的令牌发送到第一台服务器进行验证,并收到初始此令牌到此服务器的答案?
解决方案
您可以参考以下步骤在 ASP.NET Core 中使用 JWT 身份验证。
使用 JWT 承载选项配置身份验证架构。
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); services.AddControllersWithViews(); }
在此示例中,我将这些值存储在 appsettings.json 文件中。
{ "Jwt": { "Key": "ThisismySecretKey", "Issuer": "Test.com" } }
在启动类的 Configure 方法中调用 app.UseAuthentication() 方法。
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
生成 JSON Web 令牌
using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Test.Models; namespace Test.Controllers { [Route("api/[controller]")] [ApiController] public class LoginController : ControllerBase { private IConfiguration _config; public LoginController(IConfiguration config) { _config = config; } [AllowAnonymous] [HttpPost] public IActionResult Login([FromBody] UserModel login) { IActionResult response = Unauthorized(); var user = AuthenticateUser(login); if (user != null) { var tokenString = GenerateJSONWebToken(user); response = Ok(new { token = tokenString }); } return response; } private string GenerateJSONWebToken(UserModel userInfo) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username), new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress), new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(token); } private UserModel AuthenticateUser(UserModel login) { UserModel user = null; //Validate the User Credentials //Demo Purpose, I have Passed HardCoded User Information if (login.Username == "Jignesh") { user = new UserModel { Username = "Jignesh Trivedi", EmailAddress = "test.btest@gmail.com" }; } return user; } } }
然后,如果您请求“API/login”方法生成令牌,则必须在请求正文中传递以下 JSON。
{"username": "Jignesh", "password": "password"}
然后,在获取 JWT 令牌后,您可以在访问其他 API 控制器时在请求标头中添加“授权”属性。
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY
如果您的意思是对多个 API 应用程序使用一个 JWT 令牌,据我所知,JWT 令牌旨在用于受众 (aud) 声明所指示的特定服务或应用程序。您不能将相同的令牌用于其他应用程序或服务。
更多详细信息请查看以下链接:
推荐阅读
- airflow - 如何在没有密钥的情况下将 Airflow 连接到 AWS S3?
- java - LeanFT:无法调用具有非原始参数的方法:没有使用 cookie 注册对象:[object Object]
- php - 如何在 Smarty 代码中查看数组详细信息?
- serverless-framework - 未找到无服务器命令“项目”
- android - 无法在 DomainComponent 中提供应用程序(Dagger 2)
- android - 以编程方式为片段设置上下文以进行测试
- python - 测试完成后,Django TestCase 不会破坏测试数据
- javascript - 是否可以在 AngularJS 中调用函数并显示值
- magento2 - Magento2 - 批量操作消费者问题
- php - Extbase:在同一模型上使用 1:n 时排序混合