2 # Copyright vanoudt@gmail.com 2014
3 # Based on persona code from chris@bigballofwax.co.nz 2013
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>.
21 # Basic OAuth2/OpenID Connect authentication for google goes like this
23 # The first thing that happens when this script is called is
24 # that one gets redirected to an authentication url from google
26 # If successful, that then redirects back to this script, setting
27 # a CODE parameter which we use to look up a json authentication
28 # token. This token includes an encrypted json id_token, which we
29 # round-trip back to google to decrypt. Finally, we can extract
30 # the email address from this.
34 use CGI qw ( -utf8 escape );
35 use C4::Auth qw{ checkauth get_session get_template_and_user };
41 use HTTP::Request::Common qw{ POST };
43 use MIME::Base64 qw{ decode_base64url };
46 'https://accounts.google.com/.well-known/openid-configuration';
47 my $authendpoint = '';
48 my $tokenendpoint = '';
49 my $scope = 'openid email profile';
50 my $host = C4::Context->preference('OPACBaseURL') // q{};
51 my $restricttodomain = C4::Context->preference('GoogleOpenIDConnectDomain')
54 # protocol is assumed in OPACBaseURL see bug 5010.
55 my $redirecturl = $host . '/cgi-bin/koha/svc/auth/googleopenidconnect';
56 my $issuer = 'accounts.google.com';
57 my $clientid = C4::Context->preference('GoogleOAuth2ClientID');
58 my $clientsecret = C4::Context->preference('GoogleOAuth2ClientSecret');
60 my $ua = LWP::UserAgent->new();
61 my $response = $ua->get($discoveryDocURL);
62 if ( $response->is_success ) {
63 my $json = decode_json( $response->decoded_content );
64 if ( exists( $json->{'authorization_endpoint'} ) ) {
65 $authendpoint = $json->{'authorization_endpoint'};
67 if ( exists( $json->{'token_endpoint'} ) ) {
68 $tokenendpoint = $json->{'token_endpoint'};
75 my $cgi_query = shift;
77 $cgi_query->delete('code');
78 $cgi_query->param( 'OpenIDConnectFailed' => $reason );
79 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
81 template_name => 'opac-user.tt',
86 $template->param( 'invalidGoogleOpenIDConnectLogin' => $reason );
87 $template->param( 'loginprompt' => 1 );
88 output_html_with_http_headers $cgi_query, $cookie, $template->output, undef, { force_no_caching => 1 };
92 if ( defined $query->param('error') ) {
94 'An authentication error occurred. (Error:'
95 . $query->param('error')
98 elsif ( defined $query->param('code') ) {
99 my $stateclaim = $query->param('state');
100 my $session = get_session( $query->cookie('CGISESSID') );
101 if ( $session->param('google-openid-state') ne $stateclaim ) {
102 $session->clear( ["google-openid-state"] );
105 'Authentication failed. Your session has an unexpected state.' );
107 $session->clear( ["google-openid-state"] );
110 my $code = $query->param('code');
111 my $ua = LWP::UserAgent->new();
112 if ( $tokenendpoint eq q{} ) {
113 loginfailed( $query, 'Unable to discover token endpoint.' );
119 client_id => $clientid,
120 client_secret => $clientsecret,
121 redirect_uri => $redirecturl,
122 grant_type => 'authorization_code',
126 my $response = $ua->request($request)->decoded_content;
127 my $json = decode_json($response);
128 if ( exists( $json->{'id_token'} ) ) {
129 if ( lc( $json->{'token_type'} ) ne 'bearer' ) {
131 'Authentication failed. Incorrect token type.' );
133 my $idtoken = $json->{'id_token'};
135 # Normally we'd have to validate the token - but google says not to worry here (Avoids another library!)
136 # See https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo for rationale
137 my @segments = split( '\.', $idtoken );
138 unless ( scalar(@segments) == 3 ) {
140 'Login token broken: either too many or too few segments.' );
142 my ( $header, $claims, $validation ) = @segments;
143 $claims = decode_base64url($claims);
144 my $claims_json = decode_json($claims);
145 if ( ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) )
146 && ( $claims_json->{'iss'} ne $issuer ) )
149 "Authentication failed. Issuer of authentication isn't Google."
152 if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) {
153 warn "Audience is an array of size: "
154 . scalar( @$claims_json->{'aud'} );
155 if ( scalar( @$claims_json->{'aud'} ) > 1 )
156 { # We don't want any other audiences
158 "Authentication failed. Unexpected audience provided." );
161 if ( ( $claims_json->{'aud'} ne $clientid )
162 || ( $claims_json->{'azp'} ne $clientid ) )
165 "Authentication failed. Unexpected audience." );
167 if ( $claims_json->{'exp'} < time() ) {
168 loginfailed( $query, 'Sorry, your authentication has timed out.' );
171 if ( exists( $claims_json->{'email'} ) ) {
172 my $email = $claims_json->{'email'};
173 if ( ( $restricttodomain ne q{} )
174 && ( index( $email, $restricttodomain ) < 0 ) )
177 'The email you have used is not valid for this library. Email addresses should conclude with '
183 'The email address you are trying to use is not associated with a borrower at this library.';
184 my $auto_registration = C4::Context->preference('GoogleOpenIDConnectAutoRegister') // q{0};
185 my $borrower = Koha::Patrons->find( { email => $email } );
186 if (! $borrower && $auto_registration==1) {
187 my $firstname = $claims_json->{'given_name'} // q{};
188 my $surname = $claims_json->{'family_name'} // q{};
189 my $delimiter = $firstname ? q{.} : q{};
190 my $userid = $firstname . $delimiter . $surname;
191 my $categorycode = C4::Context->preference('GoogleOpenIDConnectDefaultCategory') // q{};
192 my $patron_category = Koha::Patron::Categories->find( $categorycode );
193 my $branchcode = C4::Context->preference('GoogleOpenIDConnectDefaultBranch') // q{};
194 my $library = Koha::Libraries->find( $branchcode );
195 if (defined $patron_category && defined $library) {
196 my $password = undef;
197 # TODO errors handling!
198 my $borrower = Koha::Patron->new({
199 firstname => $firstname,
202 categorycode => $categorycode,
203 branchcode => $branchcode,
205 password => $password
208 $error_feedback = 'The GoogleOpenIDConnectDefaultBranch or GoogleOpenIDConnectDefaultCategory system preferences are not configured properly. Please contact the library with this error message.';
211 my ( $userid, $cookie, $session_id ) =
212 checkauth( $query, 1, {}, 'opac', $email );
213 if ($userid) { # A user with this email is registered in koha
215 #handle redirect to main.pl, for private opac
217 if (C4::Context->preference('OpacPublic') ) {
218 $uri = '/cgi-bin/koha/opac-user.pl';
220 $uri = '/cgi-bin/koha/opac-main.pl';
222 print $query->redirect(
228 loginfailed( $query, $error_feedback );
234 'Unexpectedly, no email seems to be associated with that acccount.'
239 loginfailed( $query, 'Failed to get proper credentials from Google.' );
243 my $session = get_session( $query->cookie('CGISESSID') );
244 my $openidstate = 'auth_';
245 $openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32;
246 $session->param( 'google-openid-state', $openidstate );
249 my $prompt = $query->param('reauthenticate') // q{};
250 if ( $authendpoint eq q{} ) {
251 loginfailed( $query, 'Unable to discover authorisation endpoint.' );
253 my $authorisationurl =
255 . 'response_type=code&'
257 . escape($redirecturl) . q{&}
259 . escape($clientid) . q{&}
261 . escape($scope) . q{&}
263 . escape($openidstate);
264 if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) {
265 $authorisationurl .= '&prompt=' . escape($prompt);
267 print $query->redirect($authorisationurl);