.net core 2.1 中 jwt 的 x509certificate2 标志 [英] x509certificate2 sign for jwt in .net core 2.1

查看:41
本文介绍了.net core 2.1 中 jwt 的 x509certificate2 标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 JWT 库制作 JWT 令牌,但由于各种原因,我必须手工制作.我有一个包含公钥和私钥的 X509Certificate2 对象 - 我可以在网上找到大量不同的代码,这些代码使用其中的私钥进行签名 - 有时将其转换为 rsacryptoprovider,有时将其作为 xml 拉出 - 我我发现了大约十种不同的方法.

I can make a JWT token using the JWT libraries, but for various reasons I'm have to make one by hand. I have an X509Certificate2 object with both public and private keys in it - and I can find heaps of different code online that uses the privatekey out of that to sign - sometimes by casting it to rsacryptoprovider, sometimes by pulling it out as xml - I've found about ten different methods.

所有这些都在 .net 框架中工作.没有我在 net core 2.1 中尝试过的东西(即使是那些明确说它们是用于 .net core 的).私钥对象是一个 RSACng,而不是一个密码提供者——任何调用获取 xml 或私有属性的方法的尝试都表示不支持操作——并且 RsaCng 上没有签名方法.

All of them work in .net framework. nothing that I've tried works in net core 2.1 (even the ones that explicitly say they are for .net core). The private key object is a RSACng, not a cryptoprovider - any attempt to call methods that get at the xml or the private properties say operation not supported - and the RsaCng doesn't have a sign method on it.

我有一堆字节作为有效载荷,以及一个完全填充的 X509certificate2 对象(从 .pfx 文件中读取)——我想要的只是对一个字符串进行签名.有什么想法吗?

I have a bunch of bytes as a payload, and a fully populated X509certificate2 object (read from a .pfx file) - and all I want is to sign a string. Any ideas?

推荐答案

结果比我想象的要容易 - 我使用的是 System.IdentityModel.Tokens.JWT - 出于某种原因,salesforce 不喜欢它产生的 JWTJWT 功能(可能是因为它添加了大量其他属性)但无论如何 - 我追踪到它所做的代码 - 你可以使用它的实用程序 - 所以如果你自己创建 JWT 有效负载 - 以下代码会生成一个有效的 JWT:

turns out to be easier than I thought - I was using System.IdentityModel.Tokens.JWT - for some reason salesforce doesn't like the JWT it produces from the JWT functions (possibly because it adds heaps of other attributes) but anyway - I traced into the code of what it does - and you can use utilities from it - so if you create the JWT payload yourself - the following code produces a valid JWT:

    var unsigned = Base64UrlEncoder.Encode(header) + "." + Base64UrlEncoder.Encode(payload);
    var x509 = new X509Certificate2(pfxFilename, certificatePassword);
    var signingCredentials = new X509SigningCredentials(x509, "RS256");
    var signature  = JwtTokenUtilities.CreateEncodedSignature(unsigned, signingCredentials);
    return unsigned + "." + signature;

这篇关于.net core 2.1 中 jwt 的 x509certificate2 标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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