Mojo::JWT - error handling

87 views
Skip to first unread message

Luc Larochelle

unread,
May 18, 2018, 3:57:11 PM5/18/18
to Mojolicious
I'm using Mojo::JWT to produde a token and verify authorization on routes (using the given token, with the same secret)

Thing is , when the token is invalid, an error is being thrown and the application crashes. I'd like to contain the error and deal with it.

What am I missing ? Here's the sample code



use Mojo::JWT;
use Mojolicious::Lite;
use Data::Dumper;

helper check_token => sub  {

        my $self = shift;
        my $token = $self->req->headers->authorization;
        my $jwt = Mojo::JWT->new(secret => 'mytest');
        return $jwt->decode($token);

};

any '/auth' => sub {
        my $c = shift;
        my $claims = $c->check_token;

        if (!($claims)) {
                $c->render(json => {status => "error", data => { message => "Please authenticate" }});
        } else {
                $c->render(json => $claims);
        }

};

Luc Larochelle

unread,
May 18, 2018, 4:00:13 PM5/18/18
to Mojolicious
Sorry here's the error ...


[Fri May 18 15:48:37 2018] [debug] POST "/auth"
[Fri May 18 15:48:37 2018] [debug] Routing to a callback
[Fri May 18 15:48:37 2018] [error] Failed HS validation at /srv/ccdapi/temp/jwt.pl line 18.

[Fri May 18 15:48:37 2018] [debug] Template "exception.development.html.ep" not found
[Fri May 18 15:48:37 2018] [debug] Template "exception.html.ep" not found
[Fri May 18 15:48:37 2018] [debug] Rendering template "mojo/debug.html.ep"
[Fri May 18 15:48:37 2018] [debug] Rendering template "mojo/menubar.html.ep"
[Fri May 18 15:48:37 2018] [debug] Your secret passphrase needs to be changed
[Fri May 18 15:48:37 2018] [debug] 500 Internal Server Error (0.064189s, 15.579/s)

Scott Wiersdorf

unread,
May 18, 2018, 4:58:02 PM5/18/18
to Mojolicious
Mojo::JWT::decode can die, so you'll want to wrap that in an eval() and trap the exception.

Scott

Luc Larochelle

unread,
May 23, 2018, 1:23:54 PM5/23/18
to Mojolicious
Hi Scott,

I tried this and it would still die. Can you provide a snippet ? I've used eval only once, based on code example I was working on.

Luc Larochelle

unread,
May 24, 2018, 4:20:51 PM5/24/18
to Mojolicious
Hi Scott,

Sorry about this. I reviewed the doc on "eval" and it's working now.

        eval {my $status = $jwt->decode($token);};
        return 0 if $@;
        return $status;
Reply all
Reply to author
Forward
0 new messages