Skip to content

Instantly share code, notes, and snippets.

@leejo
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leejo/d121db047dfd40124570 to your computer and use it in GitHub Desktop.
Save leejo/d121db047dfd40124570 to your computer and use it in GitHub Desktop.
Mojo + Swagger2 + Authorization

In swagger.yaml - note use of x-mojo-privilege key under the route method, leave this blank for routes that don't require a privilege to access:

paths:
    /foo:
        get:
            x-mojo-controller: "MyApp::API::Foo"
            x-mojo-around-action: "MyApp::API::check_api_priv"
            x-mojo-privilege: "get:foo"
            operationId: get
            summary: |
                The details of foo
            parameters:
            tags:
                - Foo
            responses:
                200:
                    description:.

In MyApp::API, requires Mojolicious::Plugin::Authorization to get at has_priv helper:

sub check_api_priv {
    my ( $next,$c,$action_spec ) = @_;

    if ( my $privilege = $action_spec->{"x-mojo-privilege"} ) {
        if ( ! $c->has_priv( $privilege ) ) {
            $c->app->log->debug( "API call but $privilege priv missing" );
            return $c->render_swagger(
                { errors => [{ message => "Denied ($privilege)" }] },
                {},
                401,
            );
        }
    }

    return $next->( $c );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment