来自文件的 .NET Core IssuerSigningKey 用于 JWT 不记名身份验证 [英] .NET Core IssuerSigningKey from file for JWT Bearer Authentication

查看:18
本文介绍了来自文件的 .NET Core IssuerSigningKey 用于 JWT 不记名身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 JWT 不记名令牌身份验证的签名密钥的实现(或理解)而苦苦挣扎.我希望有人可以帮助我或解释我的误解.

I am struggling with the implementation (or the understanding) of signing keys for JWT Bearer Token authentication. And I hope somebody can help me or explain me what I am missunderstanding.

在过去的几周里,我爬取了大量的教程,并设法让一个自定义的 Auth-Controller 运行,它发出我的令牌并设法设置 JWT 不记名身份验证来验证标头中的令牌.

The last few weeks I crawled tons of tutorials and managed to get a custom Auth-Controller running which issues my tokens and managed to set up the JWT bearer authentication to validate the tokens in the header.

有效.

我的问题是,所有示例和教程要么生成随机或内存(颁发者)签名密钥,要么使用硬编码的密码"字符串,或者从某个配置文件中获取它们(在代码示例中查找密码").

My problem is that all examples and tutorials either generate random or inmemory (issuer) signing keys or use hardcoded "password" strings or take them from some config file (look for "password" in the code samples).

我对验证设置的意思(在 StartUp.cs 中):

What I mean for validation setup (in the StartUp.cs):


  //using hardcoded "password"
  SecurityKey key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes("password"));

  app.UseJwtBearerAuthentication(new JwtBearerOptions
  {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidIssuer = "MyIssuer",
      ValidateAudience = true,
      ValidAudience = "MyAudience",
      ValidateLifetime = true,
      IssuerSigningKey = key
    }
  });

在 AuthController 中创建令牌:

In the AuthController creating the token:


  //using hardcoded password
  var signingKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes("password"));
  SigningCredentials credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

  var jwt = new JwtSecurityToken     // Create the JWT and write it to a string
  (
    issuer: _jwtTokenSettings.Issuer,
    audience: _jwtTokenSettings.Audience,
    claims: claims,
    notBefore: now,
    expires: now.AddSeconds(_jwtTokenSettings.LifetimeInSeconds),
    signingCredentials: credentials
  );

这个问题中,他们使用了:

RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

我的(当前)假设是,在生产中您不应该使用硬编码字符串或配置文件中的字符串作为令牌签名密钥.而是使用一些证书文件???我错了吗?

My (current) assumptions was that in production you should not use hardcoded strings or strings from config files for the token signing keys. But instead use some certificate files??? Am I wrong?

所以我尝试用在身份验证控制器中工作的证书替换字符串:

So I tried to replace the strings with a certificate which works in the auth controller:


  //using a certificate file
  X509Certificate2 cert = new X509Certificate2("MySelfSignedCertificate.pfx", "password");
  X509SecurityKey key = new X509SecurityKey(cert);
  SigningCredentials credentials = new SigningCredentials(key, "RS256");

  var jwt = new JwtSecurityToken      // Create the JWT and write it to a string
  (
     issuer: _jwtTokenSettings.Issuer,
     audience: _jwtTokenSettings.Audience,
     claims: claims,
     notBefore: now,
     expires: now.AddSeconds(_jwtTokenSettings.LifetimeInSeconds),
     signingCredentials: credentials
  );

但似乎没有办法使用证书进行验证.

But there seems no way to get the validation using a certificate.


  X509Certificate2 cert = new X509Certificate2("MySelfSignedCertificate.pfx", "password");
  SecurityKey key == // ??? how to get the security key from file (not necessarily pfx)

  app.UseJwtBearerAuthentication(new JwtBearerOptions
  {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidIssuer = "MyIssuer",
      ValidateAudience = true,
      ValidAudience = "MyAudience",
      ValidateLifetime = true,
      IssuerSigningKey = key
    }
  });

我应该使用证书作为签名密钥,我错了吗?当身份验证控制器位于与消费/安全 Web api 不同的服务器上时,我还能如何更改生产中的签名密钥(可能是一次,而不是现在)?

Am I wrong that I should use certificates for the signing keys? How else would I change the signing keys in production when the auth controller is on a different server than the consuming/secured web api (may one time, not now)?

看来我也错过了获得这个问题工作.

It seems I also miss the point (required steps) to get the answer of this question working.

现在我让它运行了,如果它应该是这样,我仍然没有抓住重点?

Now I got it running I am still missing the point if it should be like that?

对于所有使用它的人,它在从 Visual Studio 启动时有效,但在部署到服务器/天蓝色后显示找不到文件":

For all those using this and it works when started from Visual Studio but after deployment to a server / azure it says "File not found":

阅读并投票赞成这个问题:X509 证书未加载私有服务器上的密钥文件

read and upvote this question: X509 certificate not loading private key file on server

公钥不需要在 API 端.它将通过身份验证服务器的发现端点自动检索.

The public key does not need to be on the API side. It will be retrieved via the discovery endpoint of the authentication server automatically.

推荐答案

天哪,就这么简单:

SecurityKey key = new X509SecurityKey(cert);

或作为上面的完整示例:

Or as complete sample from above:

X509Certificate2 cert = new X509Certificate2("MySelfSignedCertificate.pfx", "password");
SecurityKey key = new X509SecurityKey(cert); //well, seems to be that simple
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "MyIssuer",
        ValidateAudience = true,
        ValidAudience = "MyAudience",
        ValidateLifetime = true,
        IssuerSigningKey = key
     }
});

这篇关于来自文件的 .NET Core IssuerSigningKey 用于 JWT 不记名身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆