The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Swagger2::Guides::ProtectedApi - Protected API Guide

OVERVIEW

It is possible to protect your API: You can either use a "Custom route" or an "Around action hook". Both can serve the same purpose, but the around action hook can be customized for every API resource.

TUTORIAL

Around action hook

The x-mojo-around-action value is optional, but can hold the name of a method to call, which wraps around the autogenerated action which does input and output validation. This means that any data sent to the server is not yet converted into $input to your action.

Here is an example method which match the x-mojo-around-action from "Swagger specification", MyApp::authenticate_api_request:

  package MyApp;

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

    # Go to the action if the Authorization header is valid
    return $next->($c) if $c->req->headers->authorization eq "s3cret!";

    # ...or render an error if not
    return $c->render_swagger(
      {errors => [{message => "Invalid authorization key", path => "/"}]},
      {},
      401
    );
  }

x-mojo-around-action is also inherited from most levels, meaning that you define it globally for your whole API if you like:

  {
    "x-mojo-around-action": "MyApp::protect_any_resource",
    "paths": {
      "/pets": {
        "x-mojo-around-action": "MyApp::protect_any_method_under_foo",
        "get": {
          "x-mojo-around-action": "MyApp::protect_just_this_resource"
        }
      }
    }
  }

Custom route

  use Mojolicious::Lite;

  my $route = app->routes->under->to(
    cb => sub {
      my $c = shift;
      return 1 if $c->param('secret');
      return $c->render(json => {error => "Not authenticated"}, status => 401);
    }
  );

  plugin Swagger2 => {
    route => $route,
    url   => "data://api.json",
  };

  __DATA__
  @@ api.json
  {"swagger":"2.0", ...}

AUTHOR

Jan Henning Thorsen - jhthorsen@cpan.org