首页 > 解决方案 > 如何使用来自 One Api 的一个 jwt 令牌来验证本地企业应用程序 asp.net 核心中的所有 API(不使用 identityserver)

问题描述

我需要为本地应用程序中的所有 api 运行 Api 身份验证服务器(使用 jwt)。如何在不使用身份服务器的情况下创建它?如何在其他 API 上验证初始令牌?如何将接收到的令牌发送到第一台服务器进行验证,并收到初始此令牌到此服务器的答案?

标签: asp.net-core

解决方案


您可以参考以下步骤在 ASP.NET Core 中使用 JWT 身份验证。

  1. 使用 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();
    
    }
    
  2. 在此示例中,我将这些值存储在 appsettings.json 文件中。

     {
         "Jwt": {
           "Key": "ThisismySecretKey",
           "Issuer": "Test.com"
         }
     }
    
  3. 在启动类的 Configure 方法中调用 app.UseAuthentication() 方法。

         app.UseRouting();
    
         app.UseAuthentication();
         app.UseAuthorization();
    
         app.UseEndpoints(endpoints =>
         {
             endpoints.MapControllerRoute(
                 name: "default",
                 pattern: "{controller=Home}/{action=Index}/{id?}");
         });
    
  4. 生成 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) 声明所指示的特定服务或应用程序。您不能将相同的令牌用于其他应用程序或服务。

更多详细信息请查看以下链接:

ASP.NET Core 中的 JWT 身份验证

多个网站的 JWT 令牌


推荐阅读