How can I create a signed JWT using npm Jose and then verify this token? - node.js

I am struggling to understand how to use the npm jose module (https://www.npmjs.com/package/jose) to create and verify signed JWT tokens in my Node application. My scenario is this: I want to sign an authenticated request to access a resource. I can successfully create a JWT claim for this request grant token that respects the properties of “its” and “aud”, “exp”, etc. but I want to sign it (to wit, using the SignJWT object and the ‘sign’ method) so that when it gets passed back to my server as a request I can validate it and grant or reject access.
The “sign” method doesn’t seem to like anything I pass it for the ‘key’ parameter (I am not passing any options — maybe I should be, but what?).
I am attempting to use RSA key pairs. I want to sign with the private key and verify with the public key. For my immediate need, I suppose I could use a symmetric key instead, but I am thinking of some other future scenarios where I will want this classic PKCS relationship of certificate keys. And at any rate, I don’t think this choice has anything to do with the current roadblock to my progress.
I first tried to use jose/util/generate_key_pair to create my public/private pair. But when I went to use the key, the error informed me this was not supported by my implementation. So I switched to trying to create a ‘pem’ cert outside of my app and applying that (as text), but that also failed. The ‘sign’ method reports that the key must be a ‘KeyLike’, ‘CryptoKey’, or ‘Uint8Array’ type. Well, the UInt8Array (node buffer) is not enough type information: it doesn’t speak to what is in that buffer, and “KeyLike” is such a vague definition that it’s ignorable. After beseeching the oracles of the search engines, I found I could create a key pair in CryptoKey format using the following from Node APIs:
crypto.webcrypto.subtle.generateKey(
{
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
[‘sign’, ‘verify’]
).then((pair:any) => {
serverInstance.keyPair = pair
})
But, still, when I get to the signing part:
siaToken.sign(serverInstance.keyPair.privateKey).then(signature => {
I get an exception that reports
“TypeError: CryptoKey does not support this operation”
Thinking this might have to do with the ‘usages’ parameter of generateKey, I tried various values there, but with no success.
So, I am flummoxed. Can anyone tell me how to (a) best produce a pair of keys for this purpose and (b) how to apply these for JWT signing?

I have also struggled with signing and verifying JWT using jose but was finally able to succeed with HS256 symmetric key encryption. I produced it by following steps (I am using jose-node-cjs-runtime for Node.js only use case. Feel free to replace with desired package. Also please note that I have found that these codes are working for Node.js version 16.7.0, 16.9.0 so please ensure that any of them is installed. If you want to deploy these changes to production environment, then also you have to ensure the deploy environment has the same Node.js version. One way this can be achieved is by mentioning Node.js version in engines key in package.json):
Add Required imports
// library for generating symmetric key for jwt
const { createSecretKey } = require('crypto');
// library for signing jwt
const { SignJWT } = require('jose-node-cjs-runtime/jwt/sign');
// library for verifying jwt
const { jwtVerify } = require('jose-node-cjs-runtime/jwt/verify');
Create Secret key of type KeyObject
KeyObject is recommended by Node.js for using when generating symmetric, asymmetric keys. Use following code to generate and store symmetric key object of type KeyObject in secretKey.
const secretKey = createSecretKey(process.env.JWT_SECRET, 'utf-8');
Replace process.env.JWT_SECRET with a sufficiently long string. It needs to be sufficiently long (use strings of length at least 32) otherwise there will be following error thrown when signing the JWT: HS256 requires symmetric keys to be 256 bits or larger
Sign the JWT
(async () => {
const token = await new SignJWT({ id: '12345' }) // details to encode in the token
.setProtectedHeader({ alg: 'HS256' }) // algorithm
.setIssuedAt()
.setIssuer(process.env.JWT_ISSUER) // issuer
.setAudience(process.env.JWT_AUDIENCE) // audience
.setExpirationTime(process.env.JWT_EXPIRATION_TIME) // token expiration time, e.g., "1 day"
.sign(secretKey); // secretKey generated from previous step
console.log(token); // log token to console
})();
Verify the JWT
We will use the same symmetric key stored in secretKey for verification purpose as well. Following code can be used to extract token from request header (in an Express app) and validate the token:
(async () => {
// extract token from request
const token = req.header('Authorization').replace('Bearer ', '');
try {
// verify token
const { payload, protectedHeader } = await jwtVerify(token, secretKey, {
issuer: process.env.JWT_ISSUER, // issuer
audience: process.env.JWT_AUDIENCE, // audience
});
// log values to console
console.log(payload);
console.log(protectedHeader);
} catch (e) {
// token verification failed
console.log("Token is invalid");
}
})();

By far the easiest way to generate the key material is to use generateKeyPair. The method is runtime agnostic and only requires a single argument - the Algorithm Identifier you wish to use the target key pair with. If you're bringing your own keys tho you must be aware of the different requirements for the key in order to be usable by the algorithm.
Not every runtime's crypto capabilities can support every algorithm, the list of available algorithms per runtime is available here.
Furthermore - importing SPKI/PKCS8 encoded key material is platform-specific and done through platform-specific APIs. The ways one can end up with KeyLike (type alias for CryptoKey (web), KeyObject (node), or Uint8Array (symmetric secrets) is documented in, well, KeyLike alias documentation linked from every function doc that uses it.
If you were to provide any actual reproduction code for your steps I would be happy to help.
The ‘sign’ method reports that the key must be a ‘KeyLike’, ‘CryptoKey’, or ‘Uint8Array’ type.
I'm fairly sure it says KeyObject at runtime, KeyLike is merely a type alias covering all the different types of inputs applicable for the different algorithms and runtimes.

Related

Read claims without verification. , Understanding the Result return

I'm working JWT's in Rust and have come across a situation that I'm having some issues navigating. I'm new to both Rust and JWT's, so bare with me.
I'm using the jwt crate found here.
What I want to do is create a Signed JWT that contains a header and claims. The claims have a single field, issuer. I'm able to issue a new token with no issue.
fn issue_token(user_id: &str) -> Result<String, &'static str> {
let header: Header = Default::default();
let claims = RegisteredClaims {
issuer: Some("user who issued token".into()),
subject: Some(user_id.into()),
..Default::default()
};
let unsigned_token = Token::new(header, claims);
let key: Hmac<Sha256> =
Hmac::new_from_slice("secret_key".as_bytes()).map_err(|_e| "Invalid key")?;
let signed_token = unsigned_token
.sign_with_key(&key)
.map_err(|_e| "Sign error")?;
Ok(signed_token.into())
}
The issuer claim is important. As there are different processes that have their own tokens. All of the issuers have already registered their secret with the main server. Now, other users will connect to a specific issuer, validate who the user is, and will issue a JWT that has been signed. The user does not know what the secret is, that's only known between the issuer and the server.
What I'm trying to do, on the server-side, is read the claims to identify who the issuer is. Once I know who the issuer is I then know what secret to use to verify the signature.
I have no issues verifying the token, and once I verify the token, I'm able to read the claims. But I need to read the claims first, and then verify the token.
beyond the basic examples for signing and verifying, the documentation is clear to me.
looking at the documentation for the crate, here, I've not been able to figure out how to implement what I'm attempting to do.
I've found what I believe to be what I'm looking for, here, parse_unverified or Unverified, but I'm struggling to figure out how to use either.
parse_unverified looks to be the more promising of the two as the documentation states Not recommended. Parse the header and claims without checking the validity of the signature
Does anyone have any experience with Rust and the jwt crate?
I believe I've gotten it partially figured out.
it starts with importing the correct crate options
use jwt::{Claims, Error, Header, RegisteredClaims, Token, Unverified, VerifyWithKey};
I can then create a new variable, like
let unverified: Result<Token<Header, Claims, Unverified<'_>>, Error> =
Token::parse_unverified(token);
Now this works, it builds and runs just fine. What I'm having an issue with now is actually parsing unverified now.
the more that I look at it, I think this might have less to do with JWT and more to do with standard Rust operations. As its returning a Result.
Any insight?
It's a standard Result, so you have to unwrap that as usual with ? to get at the Token inside. Even though this doesn't verify the signature, it can still fail due to invalid base64/JSON encoding or JWT framing. (If there's an error here the token isn't even structurally valid, so there's no point in going further.)
let unverified: Token<Header, Claims, _> = Token::parse_unverified(token)?;
Now you can use any facilities provided by Token on unverified, e.g. unverified.claims().
You might want to parse with RegisteredClaims though, which gives you easier access to the issuer field:
let unverified: Token<Header, RegisteredClaims, _> =
Token::parse_unverified(token)?;
let issuer = unverified.claims().issuer.as_ref()
.ok_or(MissingIssuerError)?;
issuer will be a &String. (MissingIssuerError is a placeholder for an error you can raise if the issuer field is absent.)

OpenPGP.js says elgamal keys are considered too weak

We are using PGP encryption to encrypt files before transfer. We are using the npm package OpenPGP.js to encrypt the files using a public key from the recipient. I have exported the public key in armored format to use with openpgp.encrypt function.
Here is the code to encrypt the file:
const publicKey = await openpgp.readKey({ armoredKey: key.publicKey });
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: readStream }),
encryptionKeys: publicKey
});
However the function call produces this error:
Error: Error encrypting message: Could not find valid encryption key
packet in key ea8be7d9f2fd53a7: elgamal keys are considered too weak.
The output of gpg --list-keys gives the following information
pub dsa1024 2010-07-23 [SCA]
ABCDEFGHIJK
uid [ unknown] my recipient <my.recipient#email.com>
sub elg2048 2010-07-23 [E]
I'm able to encrypt a file using GnuPG, but OpenPGP does not seem to like the public key. Is this error message valid? Do I need to request another key from the client, or is there a way to bypass this error message?
*Edit: After some research I have found that DSA-1024/(ElGamal-anything) is not safe anymore, so I'll probably have to request new keys be made.
OpenPGP implementations have different security considerations, and OpenPGP.js seems decided to reject DSA/ElGamal by default via this PR: https://github.com/openpgpjs/openpgpjs/pull/1264/files#
However it is possible to override this behaviour via config, examples are available in tests.

How to make two factor authentication token expire after single use

I implemented two factor authentication but by following this tutorial
https://learn.microsoft.com/en-us/aspnet/identity/overview/features-api/two-factor-authentication-using-sms-and-email-with-aspnet-identity
I want to make the code expire after single use.
Right now, user receives the same code during the expiration time (which is set to 5 minutes) completes. Is there a way to make the code single use? I couldn't find anything on this subject.
There is a note in the tutorial that you linked to that says:
The 2FA codes are generated using Time-based One-time Password Algorithm and codes are valid for six minutes. If you take more than six minutes to enter the code, you'll get an Invalid code error message.
So, using this method, you cannot make the code expire after user.
You could, as an addition, keep a store of codes that have been used and check against that store before validating the code. You could allow the codes to expire out of that store after 6 minutes, which is their natural expiry time, but in the meantime use them to reject a second authentication.
Alternatively, you can choose to avoid the TOTP method and generate a random code that you store against your user before you send the SMS or email. Then you can check against that code when the user authenticates with it and delete or invalidate the code at that point. Using TOTP means that you could extend this 2FA to use an authenticator app based flow for the authentication too, which is more secure than SMS or email.
AspNetIdentity does not automatically invalidate used second factor codes, a code is always valid for a six minute window, but there is a workaround for this.
One of the inputs to the token generator is the SecurityStamp, which is stored as part of the user account. Token providers that extend the TotpSecurityStampBasedTokenProvider, like for example the EmailTokenProvider, will use the security stamp when they generate and validate a second factor code.
Thus, you can invalidate all issued tokens by changing the security stamp by calling UserManager.UpdateSecurityStampAsync(userId) after a successful two factor authentication.
There is a side effect that may not be desirable, being that other sessions will get logged out when the security stamp changes.
In the ApplicationSignInManager class, you can override TwoFactorSignInAsync and make the call there:
(Note: This is taken from AspNetIdentity, if you are using a different package, make sure to take TwoFactorSignInAsync from that instead and modify it accordingly.)
public override async Task<SignInStatus> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberBrowser)
{
var userId = await GetVerifiedUserIdAsync().WithCurrentCulture();
if (userId == null)
{
return SignInStatus.Failure;
}
var user = await UserManager.FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
return SignInStatus.Failure;
}
if (await UserManager.IsLockedOutAsync(user.Id).WithCurrentCulture())
{
return SignInStatus.LockedOut;
}
if (await UserManager.VerifyTwoFactorTokenAsync(user.Id, provider, code).WithCurrentCulture())
{
// When token is verified correctly, clear the access failed count used for lockout
await UserManager.ResetAccessFailedCountAsync(user.Id).WithCurrentCulture();
// Update the security stamp in order to invalidate all issued two factor tokens.
await UserManager.UpdateSecurityStampAsync(user.Id);
await SignInAsync(user, isPersistent, rememberBrowser).WithCurrentCulture();
return SignInStatus.Success;
}
// If the token is incorrect, record the failure which also may cause the user to be locked out
await UserManager.AccessFailedAsync(user.Id).WithCurrentCulture();
return SignInStatus.Failure;
}
If you want only the latest issued code to be valid, you should make the call to UpdateSecurityStampAsync also before any new code is generated.

Verifying JWT generated by Node in Laravel

I'm generating a token on our auth server (Node.js) in node-jsonwebtoken that will be passed to an API (PHP Laravel) and verified by tymondesigns/jwt-auth.
A token generated by tymondesigns/jwt-auth will be verified successfully by
its own verify function, node-jsonwebtoken and jwt.io.
A token generated by node-jsonwebtoken will be verified successfully by its own verify function, jwt.io, but not tymondesigns/jwt-auth.
On the Laravel server, i get the following error when I try to verify a token generated by node-jsonwebtoken:
TokenInvalidException in NamshiAdapter.php line 71:
Token Signature could not be verified.
The payloads look identical when I look at them over at jwt.io. I have even tried to generate the exact same token on the Node server by passing the same iat,sub,iss,exp,nbf and jti as generated by a working token, but tymondesigns/jwt-auth still won't accept it.
Is there anything else that could be causing this, but isn't visible in the decoded information? I'm also not 100% sure how jti works. Maybe there is something preventing this from working about that?
node-jsonwebtoken (7.1.9), tymon/jwt-auth (0.5.9), namshi/jose (5.0.2)
The last version of the namshi/jose library is 7.0.
There is also a known bugs for all ESxxx algorithms.
If you cannot verify signatures using that library, you could try with another one.
I developed a library that supports all features described in the RFCs related to the JWT, including encryption support.
The reason is, as mentioned by Spomky aswell, a bug in namshi/jose related to the iss claim. It is resolved in 7.0 which is used by tymon/jwt-auth 1.0.0-alpha.2. However, since there currently isn't a documented way to install 1.0.0-alpha.2, we probably have to wait for a stable release.
Until then, since the problem and the bug is related to the iss claim, removing the iss requirement from required_claims and generating the tokens without it solves the problem temporarily.
In my case I had a url inside the payload. PHP escapes slashes by default when encoding to JSON, while Node.js doesn't. When the verification JWT gets generated in PHP (with those extra backslashes) of course the final hashes won't match since the payload is just different. Solution is to use the JSON_UNESCAPED_SLASHES flag when converting to JSON inside your JWT library, I was using https://github.com/namshi/jose so I created a simple class like this one:
use Namshi\JOSE\SimpleJWS;
class SimpleJWSWithEncodeOptions extends SimpleJWS
{
protected static $encodeOptions = 0;
public static function setEncodeOptions($options)
{
self::$encodeOptions = $options;
}
/**
* Generates the signed input for the current JWT.
*
* #return string
*/
public function generateSigninInput()
{
$base64payload = $this->encoder->encode(json_encode($this->getPayload(), self::$encodeOptions));
$base64header = $this->encoder->encode(json_encode($this->getHeader(), self::$encodeOptions));
return sprintf("%s.%s", $base64header, $base64payload);
}
}
Then it could be used like:
SimpleJWSWithEncodeOptions::setEncodeOptions(JSON_UNESCAPED_SLASHES);
$jws = SimpleJWSWithEncodeOptions::load($token);
$jws->verify($key);
$data = $jws->getPayload();
This problem was very specific to my payload content but it could help someone

How to Prevent CSRF in Play [2.0] Using Scala?

A lot of web frameworks have a standard setup for generating forms with auth tokens.
Do I have to create such measures manually, or does Play come with a build in means of prevening CSRF?
The documentation on the Play website doesn't seem to address this.
I use the play2-authenticitytoken module:
The authenticity token is a way around one of the most serious internet security threats: CRSF attacks. It ensures that the client submitting a form is the one who received the page (and not a hacker who stole your session data).
How it works:
In a nutshell:
on every form post, we add a hidden parameter containing a uuid
the uuid is signed and its signature is stored in the session (which translated into a cookie)
When the user submits the form, we get: the uuid, the signature and the other form inputs.
We sign the incoming uuid again
Validation passes if the signatures match (session.sign=uuid.sign)
Should an attacker inject a different id, he will never figure how to generate the correct signature.
For completeness sake, I have an example here in Scala for Play 2.0
https://github.com/jacobgroundwater/Scala-Play-CSRF
This method also uses the cookie + hidden-field approach.
Example Usage
Use the SessionKey action to help sign a form:
object Application extends Controller {
def login = SessionKey{ (key,signature) =>
Action { implicit request =>
Ok( views.html.login(signature) ).withSession( key->signature )
}
}
}
When parsing forms use the following to check for the signature:
object Authenticator extends Controller {
def login = ValidateForm{
Action { implicit request =>
Ok( views.html.index("You're Loggd In") )
}
}
}
Since Play 2.1 there's support for this in the framework. Nick Carroll wrote a nice little article on how to use it:
http://nickcarroll.me/2013/02/11/protect-your-play-application-with-the-csrf-filter/

Resources