如何从单个服务终结点颁发和验证 JWT?



我已经成功地在Angular前端Web应用程序和.Net Core Web API后端(用于获取数据(之间连接了一个基于令牌的授权系统。

现在,我想将 JWT 逻辑(生成和验证(整合到第三个 Web API .Net Core 项目中。

如何将以下逻辑"移动"到单独的 Web API 中进行令牌验证?

启动中.cs:

public void ConfigureServices(IServiceCollection services)
{            
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidAudiences = new List<string> { "Audience1", "Audience2" },
ValidIssuer = "Credit Card oAuth Web API",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
};
});                        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

在控制器中:

[Authorize (Roles = "Credit Card Administrator")]
public ActionResult<string> Get(int id)
{
return "value";
}

我想保留角色的逻辑(由于在 JWT 中设置了这样的声明,因此它正在工作(:

var userClaims = new List<Claim>()
{
new Claim(JwtRegisteredClaimNames.Sub, name),
new Claim(JwtRegisteredClaimNames.Email, "user.name@company.com"),
new Claim(JwtRegisteredClaimNames.GivenName, "User Name"),
new Claim(ClaimTypes.Role, "Customer Administrator"),
new Claim(ClaimTypes.Role, "Credit Card Administrator"),
new Claim(ClaimTypes.Role, "Counter Administrator")
};
// TODO: Refactor The Following: Get token from oAuth Service (pass in Audience and Claims)
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokenOptions = new JwtSecurityToken(
issuer: "http://localhost:58726",
audience: "http://localhost:58726",
claims: userClaims,
expires: DateTime.Now.AddMinutes(20),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);

我希望这是有道理的,并感谢任何帮助。

如何将以下逻辑"移动"到单独的 Web API 中进行令牌验证?

要移动的逻辑是 ASP.NET Core 身份验证中间件的一部分,该中间件具有这些职责。

  1. 从 HTTP 请求的Authorize标头读取访问令牌(持有者令牌(,
  2. 验证该访问令牌,
  3. 显示访问令牌对Authorize属性的声明。

在这种情况下,访问令牌编码为 JWT。

听起来您想在单独的服务器上执行步骤 (2(。如果是这种情况,您可能正在寻找OAuth Introspection。

GitHub上有一些扩展。此外,AspNet.Security.OAuth.Extensions Introspection 問題和答案的 Error 將幫助您為 OAuth Introspection 配置這些分機。

最新更新