PrePAN

Sign in to PrePAN

Catalyst::Authentication::Credential::JWT authentication to a Catalyst app via JSON Web Token

Good

Synopsis

use Catalyst qw/
    Authentication
/;

__PACKAGE__->config( 'Plugin::Authentication' => {
    default_realm => 'example',
    realms => {
        example => {
            credential => {
                class => 'JWT',
                jwt_key => 'secret' # MUST be changed!!
            },
            store => {
                class => 'Minimal',
                users => {
                    bob => { password => 'bobspassword' },
                },
            },
        },
    }
});

sub foo : Local {
    my ( $self, $c ) = @_;

    $c->authenticate({}, "example");

    do_stuff();
}

# see also the tests of this module. The task of creating new tokens to users is
# up to you, but you will probably write something like this:

use JSON qw/encode_json decode_json/;
use Crypt::JWT qw/encode_jwt/;

sub auth_jwt :Chained('/') :PathPart('auth_jwt') :Args(0) :Method('POST') {
    my ($self, $c) = @_;

    my $user = $c->req->body_data->{username} // '';
    my $pass = $c->req->body_data->{password} // '';

    my $key = 'secret'; # CHANGE THIS!!!

    $c->response->content_type('application/json');

    ...
    # error checking
    # checking valid credential from db

    my $result = {};

    if ($auth_credentials_valid) {
        my $jwt_data = {
            username => $user,
        };
        $result->{jwt} = encode_jwt(
            payload => $jwt_data,
            key => $key,
            alg => $alg,
        );
    } else {
        $c->response->status(HTTP_FORBIDDEN);
        $c->response->body(encode_json({ code => HTTP_FORBIDDEN,
            message => "User not found" })."\n");
        $c->log->error("User not found");
        return;
    }

    $c->res->body(encode_json($result));
    $c->res->code(HTTP_OK);  # 200

    return;
}

Description

This authentication credential checker tries to read a JSON Web Token (JWT) from the current request, verifies its signature and looks up the user in the configured authentication store.

It provides support for authentication/authorization via JWT to Catalyst.

Comments

Please sign up to post a review.