Skip to content

Instantly share code, notes, and snippets.

@vanch
Last active May 16, 2023 13:11
Show Gist options
  • Save vanch/c1222f45e800a7e8cfa78756b6a3c0aa to your computer and use it in GitHub Desktop.
Save vanch/c1222f45e800a7e8cfa78756b6a3c0aa to your computer and use it in GitHub Desktop.
Nginx perl JWT claim logging
load_module "modules/ngx_http_perl_module.so";
http {
perl_modules perl/lib;
perl_set $jwt_value "sub {
use strict;
use warnings;
my $r = shift;
my $jwt = $r->header_in('Authorization');
$jwt =~ s/^Bearer //;
my $payload = (split(/\./, $jwt))[1];
return $payload;
}";
perl_set $claim_value "sub {
use strict;
use warnings;
use MIME::Base64 qw(decode_base64url);
use JSON::PP;
my $r = shift;
my $payload = $r->variable('jwt');
my $json = decode_json(decode_base64url($payload));
my $claim = exists $json->{email} ? $json->{email} : exists $json->{uid} ? $json->{uid} : exists $json->{tgid} ? $json->{tgid} : $json->{sub};
return $claim;
}";
map $http_authorization $jwt {
~. $jwt_value;
default -;
}
map $http_authorization $claim {
~. $claim_value;
default -;
}
log_format main '$msec $remote_addr - $remote_user "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $server_name $request_time $claim $jwt';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment