=head1 NAME Swagger2::Guides::ProtectedApi - Protected API Guide =head1 OVERVIEW It is possible to protect your API: You can either use a L</Custom route> or an L</Around action hook>. Both can serve the same purpose, but the around action hook can be customized for every API resource. =head1 TUTORIAL =head2 Around action hook The C<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 C<$input> to your action. Here is an example method which match the C<x-mojo-around-action> from L</Swagger specification>, C<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 ); } C<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" } } } } =head2 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", ...} =head1 AUTHOR Jan Henning Thorsen - C<jhthorsen@cpan.org> =cut