用于JWT承载身份验证的文件的.NET Core IssuerSigningKey [英] .NET Core IssuerSigningKey from file for JWT Bearer Authentication

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

问题描述

我正在努力实现(或理解)用于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?

因此,我尝试用在auth控制器中有效的证书替换字符串:

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
    }
  });

我是否应该为证书密钥使用证书? 当auth控制器位于与使用/安全的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
     }
});

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

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