DCIT / perl-Crypt-JWT

Other
54 stars 18 forks source link

How to generate and validate JWT use rsa algorithm? #27

Closed renyuntao closed 3 years ago

renyuntao commented 3 years ago

How to generate and validate JWT use rsa algorithm? Can you give me a example?

renyuntao commented 3 years ago

I have found the way to use Crypt::JWT module:

#!/usr/bin/perl

use strict;
use warnings;
use Crypt::JWT qw(encode_jwt decode_jwt);
use Crypt::PK::RSA;
use Data::Dumper;

####################
# Encode
####################

my $payload = {
        iss => "issuer",
        sub => "subject",
        exp => time + 86400,
};

my $keyfile = "/path/to/privateKey";
my $key = Crypt::PK::RSA->new($keyfile);
my $alg = "RS256";

my $token = encode_jwt(payload => $payload, key => $key, alg => $alg);
print "token: $token\n";

####################
# Decode
####################

my $pubkeyfile = "/path/to/publicKey";
my $pubkey = Crypt::PK::RSA->new($pubkeyfile);
my $data = decode_jwt(token => $token, key => $pubkey);
print Dumper \$data;