REST API: Checking username and password

From Koha Wiki
Jump to navigation Jump to search

Small example that uses the validateUserAndPassword operation.

  • Authenticates to the REST API using Basic Auth
  • Checks the username and password for the "koha" user

Settings:

  • RESTBasicAuth = Enable
use Modern::Perl;
use LWP::UserAgent;
use HTTP::Request::Common;
use JSON;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my $domain   = 'localhost:8080';
my $username = 'koha';
my $password = 'koha';

my %data = ( 
  'userid'   => 'koha',
  'password' => 'koha',
);

my $ua = LWP::UserAgent->new();
my $request = HTTP::Request::Common::POST(
    "http://$domain/api/v1/auth/password/validation", 
    Content_Type => 'application/json', 
    Content => to_json( \%data )
);

$request->authorization_basic( $username, $password );

say Dumper $request;

my $response = $ua->request($request);
say $response->as_string();

Expected output:

$VAR1 = bless( {
                 '_content' => '{"password":"koha","userid":"koha"}',
                 '_headers' => bless( {
                                        'authorization' => 'Basic a29oYTprb2hh',
                                        'content-length' => 35,
                                        'content-type' => 'application/json'
                                      }, 'HTTP::Headers' ),
                 '_method' => 'POST',
                 '_uri' => bless( do{\(my $o = 'http://localhost:8080/api/v1/auth/password/validation')}, 'URI::http' )
               }, 'HTTP::Request' );

HTTP/1.1 201 Created
Connection: close
Date: Fri, 05 Apr 2024 12:45:30 GMT
Server: Apache/2.4.56 (Debian)
Vary: User-Agent
Content-Length: 50
Content-Type: application/json;charset=UTF-8
Client-Date: Fri, 05 Apr 2024 12:45:30 GMT
Client-Peer: 127.0.0.1:8080
Client-Response-Num: 1

{"cardnumber":"42","patron_id":51,"userid":"koha"}