Basic Authentication in perl6 with Cro

  • A+
Category:Languages

I am looking for a simple solution to protect my routes with the Basic Authentication mechanism with Cro. In my example I'd like to see a 401 Unauthorized if you don't provide any credentials at all. If you provide wrong credentials I like to see a 403 Forbidden

In my code example I never saw the MyBasicAuth middleware being called:

class MyUser does Cro::HTTP::Auth {     has $.username; }  subset LoggedInUser of MyUser where { .username.defined }  class MyBasicAuth does Cro::HTTP::Auth::Basic[MyUser, "username"] {     method authenticate(Str $user, Str $pass --> Bool) {         # No, don't actually do this!         say "authentication called";         my $success = $user eq 'admin' && $pass eq 'secret';         forbidden without $success;         return $success     } }  sub routes() is export {     my %storage;     route {         before MyBasicAuth.new;         post -> LoggedInUser $user, 'api' {             request-body -> %json-object {                 my $uuid = UUID.new(:version(4));                 %storage{$uuid} = %json-object;                 created "api/$uuid", 'application/json', %json-object;             }         }     } } 

 


I added a little boilerplate around the code sample:

use Cro::HTTP::Router; use Cro::HTTP::Server; use Cro::HTTP::Auth::Basic;  class MyUser does Cro::HTTP::Auth {     has $.username; }  subset LoggedInUser of MyUser where { .username.defined }  class MyBasicAuth does Cro::HTTP::Auth::Basic[MyUser, "username"] {     method authenticate(Str $user, Str $pass --> Bool) {         say "authentication called";         return $user eq 'admin' && $pass eq 'secret';     } }  sub routes() {     my %storage;     route {         before MyBasicAuth.new;         post -> LoggedInUser $user, 'api' {             request-body -> %json-object {                 my $uuid = 'fake';                 %storage{$uuid} = %json-object;                 content 'application/json', %json-object             }         }     } }  my Cro::Service $app = Cro::HTTP::Server.new:     :host<localhost>, :port<10000>,     application => routes;  $app.start; react whenever signal(SIGINT) { $app.stop; exit } 

Try it with no user/pw:

$ curl --fail -H "Content-Type: application/json" -d '{"string":"hi"}' http://localhost:10000/api curl: (22) The requested URL returned error: 401 Unauthorized 

Try it with a user/pw:

$ curl --fail -H "Content-Type: application/json" -d '{"string":"hi"}' http://admin:secret@localhost:10000/api {"string": "hi"} 

The first one doesn't print anything. The second one prints "authentication called".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: