3 use Crypt::OpenSSL::X509;
8 use LWP::Simple qw(get);
9 use Date::Parse qw(str2time);
17 Google::JWT - JSON Web Token handler for Google tokens.
21 my $tok = Google->JWT->decode($token);
25 Retrieves Google's public certificates, and then retrieves the key from the
26 cert using L<Crypt::OpenSSL::X509>. Finally, uses the pubkey to decrypt a
27 Google token using L<JSON::WebToken>.
35 Retrieves a pair of JSON-encoded certificates from the given URL (defaults to
36 Google's public cert url), and returns the decoded JSON object.
44 Optional. Location where certificates are located.
45 Defaults to https://www.googleapis.com/oauth2/v1/certs.
51 Decoded JSON object containing certificates.
56 my ($self, $url) = @_;
58 $url ||= 'https://www.googleapis.com/oauth2/v1/certs';
59 return decode_json(get($url));
62 =head2 get_key_from_cert
64 Given a pair of certificates $certs (defaults to L</retrieve_certs>),
65 this function returns the public key of the cert identified by $kid.
73 Required. Index of the certificate hash $hash where the cert we want is
78 Optional. A (hashref) pair of certificates.
79 It's retrieved using L</retrieve_certs> if not given,
80 or if the pair is expired.
86 Public key of certificate.
90 sub get_key_from_cert {
91 my ($self, $kid, $certs) = @_;
93 $certs ||= $self->retrieve_certs;
94 my $cert = $certs->{$kid};
95 my $x509 = Crypt::OpenSSL::X509->new_from_string($cert);
97 if ($self->is_cert_expired($x509)) {
98 # If we ended up here, we were given
99 # an old $certs string from the user.
100 # Let's force getting another.
101 return $self->get_key_from_cert($kid);
104 return $x509->pubkey;
107 =head2 is_cert_expired
109 Returns if a given L<Crypt::OpenSSL::X509> certificate is expired.
113 sub is_cert_expired {
114 my ($self, $x509) = @_;
116 my $expiry = str2time($x509->notAfter);
118 return time > $expiry;
123 Returns the decoded information contained in a user's token.
131 Required. The user's token from Google+.
135 Optional. A public key string with which to decode the token.
136 If not given, the public key will be retrieved from $certs.
140 Optional. A pair of public key certs retrieved from Google.
141 If not given, or if the certificates have expired, a new
142 pair of certificates is retrieved.
148 Decoded JSON object from the decrypted token.
153 my ($self, $token, $certs, $pubkey) = @_;
156 my $details = decode_json(
157 MIME::Base64::decode_base64(
158 substr( $token, 0, CORE::index($token, '.') )
162 my $kid = $details->{kid};
163 $pubkey = $self->get_key_from_cert($kid, $certs);
166 return JSON::WebToken->decode($token, $pubkey);
171 Errietta Kostala <e.kostala@shadowcat.co.uk>
175 This library is free software. You can redistribute it and/or modify
176 it under the same terms as Perl itself.