Bug 25327: Do not call authenticate_api_request to render the spec
[koha.git] / C4 / Auth_with_shibboleth.pm
blob1e89020c024aca7ca3b990848d763c5afd13e2be
1 package C4::Auth_with_shibboleth;
3 # Copyright 2014 PTFS Europe
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Modern::Perl;
22 use C4::Debug;
23 use C4::Context;
24 use Koha::AuthUtils qw(get_script_name);
25 use Koha::Database;
26 use Koha::Patrons;
27 use C4::Members::Messaging;
28 use Carp;
29 use CGI;
30 use List::MoreUtils qw(any);
32 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
34 BEGIN {
35 require Exporter;
36 $debug = $ENV{DEBUG};
37 @ISA = qw(Exporter);
38 @EXPORT =
39 qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib);
42 # Check that shib config is not malformed
43 sub shib_ok {
44 my $config = _get_shib_config();
46 if ($config) {
47 return 1;
50 return 0;
53 # Logout from Shibboleth
54 sub logout_shib {
55 my ($query) = @_;
56 my $uri = _get_uri();
57 my $return = _get_return($query);
58 print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$return" );
61 # Returns Shibboleth login URL with callback to the requesting URL
62 sub login_shib_url {
63 my ($query) = @_;
65 my $target = _get_return($query);
66 my $uri = _get_uri() . "/Shibboleth.sso/Login?target=" . $target;
68 return $uri;
71 # Returns shibboleth user login
72 sub get_login_shib {
74 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
75 # to contain the login match point of the shibboleth-authenticated user. This match
76 # point is configured in koha-conf.xml
78 # Shibboleth attributes are mapped into http environmement variables, so we're getting
79 # the match point of the user this way
81 # Get shibboleth config
82 my $config = _get_shib_config();
84 my $matchAttribute = $config->{mapping}->{ $config->{matchpoint} }->{is};
86 if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
87 $debug and warn $matchAttribute . " value: " . $ENV{"HTTP_".uc($matchAttribute)};
88 return $ENV{"HTTP_".uc($matchAttribute)} || '';
89 } else {
90 $debug and warn $matchAttribute . " value: " . $ENV{$matchAttribute};
91 return $ENV{$matchAttribute} || '';
95 # Checks for password correctness
96 # In our case : does the given attribute match one of our users ?
97 sub checkpw_shib {
98 $debug and warn "checkpw_shib";
100 my ( $match ) = @_;
101 my $config = _get_shib_config();
102 $debug and warn "User Shibboleth-authenticated as: $match";
104 # Does the given shibboleth attribute value ($match) match a valid koha user ?
105 my $borrowers = Koha::Patrons->search( { $config->{matchpoint} => $match } );
106 if ( $borrowers->count > 1 ){
107 # If we have more than 1 borrower the matchpoint is not unique
108 # we cannot know which patron is the correct one, so we should fail
109 $debug and warn "There are several users with $config->{matchpoint} of $match, matchpoints must be unique";
110 return 0;
112 my $borrower = $borrowers->next;
113 if ( defined($borrower) ) {
114 if ($config->{'sync'}) {
115 _sync($borrower->borrowernumber, $config, $match);
117 return ( 1, $borrower->get_column('cardnumber'), $borrower->get_column('userid') );
120 if ( $config->{'autocreate'} ) {
121 return _autocreate( $config, $match );
122 } else {
123 # If we reach this point, the user is not a valid koha user
124 $debug and warn "User with $config->{matchpoint} of $match is not a valid Koha user";
125 return 0;
129 sub _autocreate {
130 my ( $config, $match ) = @_;
132 my %borrower = ( $config->{matchpoint} => $match );
134 while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
135 if ( any { /(^psgi|^plack)/i } keys %ENV ) {
136 $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
137 } else {
138 $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
142 my $patron = Koha::Patron->new( \%borrower )->store;
143 C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } );
145 return ( 1, $patron->cardnumber, $patron->userid );
148 sub _sync {
149 my ($borrowernumber, $config, $match ) = @_;
150 my %borrower;
151 $borrower{'borrowernumber'} = $borrowernumber;
152 while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
153 if ( any { /(^psgi|^plack)/i } keys %ENV ) {
154 $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
155 } else {
156 $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
159 my $patron = Koha::Patrons->find( $borrowernumber );
160 $patron->set(\%borrower)->store;
163 sub _get_uri {
165 my $protocol = "https://";
166 my $interface = C4::Context->interface;
167 $debug and warn "shibboleth interface: " . $interface;
169 my $uri;
170 if ( $interface eq 'intranet' ) {
172 $uri = C4::Context->preference('staffClientBaseURL') // '';
173 if ($uri eq '') {
174 $debug and warn 'staffClientBaseURL not set!';
176 } else {
177 $uri = C4::Context->preference('OPACBaseURL') // '';
178 if ($uri eq '') {
179 $debug and warn 'OPACBaseURL not set!';
183 if ($uri =~ /(.*):\/\/(.*)/) {
184 my $oldprotocol = $1;
185 if ($oldprotocol ne 'https') {
186 $debug
187 and warn
188 'Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!';
190 $uri = $2;
192 my $return = $protocol . $uri;
193 return $return;
196 sub _get_return {
197 my ($query) = @_;
199 my $uri_base_part = _get_uri() . get_script_name();
201 my $uri_params_part = '';
202 foreach my $param ( sort $query->url_param() ) {
203 # url_param() always returns parameters that were deleted by delete()
204 # This additional check ensure that parameter was not deleted.
205 my $uriPiece = $query->param($param);
206 if ($uriPiece) {
207 $uri_params_part .= '&' if $uri_params_part;
208 $uri_params_part .= $param . '=';
209 $uri_params_part .= $uriPiece;
212 $uri_base_part .= '%3F' if $uri_params_part;
214 return $uri_base_part . URI::Escape::uri_escape_utf8($uri_params_part);
217 sub _get_shib_config {
218 my $config = C4::Context->config('shibboleth');
220 if ( !$config ) {
221 carp 'shibboleth config not defined' if $debug;
222 return 0;
225 if ( $config->{matchpoint}
226 && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) )
228 if ($debug) {
229 warn "koha borrower field to match: " . $config->{matchpoint};
230 warn "shibboleth attribute to match: "
231 . $config->{mapping}->{ $config->{matchpoint} }->{is};
233 return $config;
235 else {
236 if ( !$config->{matchpoint} ) {
237 carp 'shibboleth matchpoint not defined';
239 else {
240 carp 'shibboleth matchpoint not mapped';
242 return 0;
247 __END__
249 =head1 NAME
251 C4::Auth_with_shibboleth
253 =head1 SYNOPSIS
255 use C4::Auth_with_shibboleth;
257 =head1 DESCRIPTION
259 This module is specific to Shibboleth authentication in koha and relies heavily upon the native shibboleth service provider package in your operating system.
261 =head1 CONFIGURATION
263 To use this type of authentication these additional packages are required:
265 =over
267 =item *
269 libapache2-mod-shib2
271 =item *
273 libshibsp5:amd64
275 =item *
277 shibboleth-sp2-schemas
279 =back
281 We let the native shibboleth service provider packages handle all the complexities of shibboleth negotiation for us, and configuring this is beyond the scope of this documentation.
283 But to sum up, to get shibboleth working in koha, as a minimum you will need to:
285 =over
287 =item 1.
289 Create some metadata for your koha instance (if you're in a single instance setup then the default metadata available at https://youraddress.com/Shibboleth.sso/Metadata should be adequate)
291 =item 2.
293 Swap metadata with your Identidy Provider (IdP)
295 =item 3.
297 Map their attributes to what you want to see in koha
299 =item 4.
301 Tell apache that we wish to allow koha to authenticate via shibboleth.
303 This is as simple as adding the below to your virtualhost config (for CGI running):
305 <Location />
306 AuthType shibboleth
307 Require shibboleth
308 </Location>
310 Or (for Plack running):
312 <Location />
313 AuthType shibboleth
314 Require shibboleth
315 ShibUseEnvironment Off
316 ShibUseHeaders On
317 </Location>
319 IMPORTANT: Please note, if you are running in the plack configuration you should consult https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPSpoofChecking for security advice regarding header spoof checking settings. (See also bug 17776 on Bugzilla about enabling ShibUseHeaders.)
321 =item 5.
323 Configure koha to listen for shibboleth environment variables.
325 This is as simple as enabling B<useshibboleth> in koha-conf.xml:
327 <useshibboleth>1</useshibboleth>
329 =item 6.
331 Map shibboleth attributes to koha fields, and configure authentication match point in koha-conf.xml.
333 <shibboleth>
334 <matchpoint>userid</matchpoint> <!-- koha borrower field to match upon -->
335 <mapping>
336 <userid is="eduPersonID"></userid> <!-- koha borrower field to shibboleth attribute mapping -->
337 </mapping>
338 </shibboleth>
340 Note: The minimum you need here is a <matchpoint> block, containing a valid column name from the koha borrowers table, and a <mapping> block containing a relation between the chosen matchpoint and the shibboleth attribute name.
342 =back
344 It should be as simple as that; you should now be able to login via shibboleth in the opac.
346 If you need more help configuring your B<S>ervice B<P>rovider to authenticate against a chosen B<Id>entity B<P>rovider then it might be worth taking a look at the community wiki L<page|http://wiki.koha-community.org/wiki/Shibboleth_Configuration>
348 =head1 FUNCTIONS
350 =head2 logout_shib
352 Sends a logout signal to the native shibboleth service provider and then logs out of koha. Depending upon the native service provider configuration and identity provider capabilities this may or may not perform a single sign out action.
354 logout_shib($query);
356 =head2 login_shib_url
358 Given a query, this will return a shibboleth login url with return code to page with given given query.
360 my $shibLoginURL = login_shib_url($query);
362 =head2 get_login_shib
364 Returns the shibboleth login attribute should it be found present in the http session
366 my $shib_login = get_login_shib();
368 =head2 checkpw_shib
370 Given a shib_login attribute, this routine checks for a matching local user and if found returns true, their cardnumber and their userid. If a match is not found, then this returns false.
372 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login );
374 =head2 _get_uri
376 _get_uri();
378 A sugar function to that simply returns the current page URI with appropriate protocol attached
380 This routine is NOT exported
382 =head2 _get_shib_config
384 my $config = _get_shib_config();
386 A sugar function that checks for a valid shibboleth configuration, and if found returns a hashref of it's contents
388 This routine is NOT exported
390 =head2 _autocreate
392 my ( $retval, $retcard, $retuserid ) = _autocreate( $config, $match );
394 Given a shibboleth attribute reference and a userid this internal routine will add the given user to Koha and return their user credentials.
396 This routine is NOT exported
398 =head1 SEE ALSO
400 =cut