AuthOpenIDConnect.pm 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
##@file
# OpenIDConnect authentication backend file

##@class
# OpenIDConnect authentication backend class
package Lemonldap::NG::Portal::AuthOpenIDConnect;

use strict;
use Lemonldap::NG::Portal::Simple;
use MIME::Base64;
11
use base qw(Lemonldap::NG::Portal::_OpenIDConnect);
12

Clément OUDOT's avatar
Clément OUDOT committed
13
our $VERSION = '2.0.0';
14 15

## @apmethod int authInit()
16
# Get configuration data
17 18
# @return Lemonldap::NG::Portal constant
sub authInit {
19 20
    my $self = shift;

21
    return PE_ERROR unless $self->loadOPs;
22
    return PE_ERROR unless $self->refreshJWKSdata;
23

24 25 26 27 28 29 30 31 32 33
    PE_OK;
}

## @apmethod int setAuthSessionInfo()
# Set _user value to 'anonymous' and authenticationLevel to 0
# @return Lemonldap::NG::Portal constant
sub setAuthSessionInfo {
    my $self = shift;

    $self->{sessionInfo}->{'_user'} = $self->{user};
34
    $self->{sessionInfo}->{authenticationLevel} = $self->{oidcAuthnLevel};
35

36
    $self->{sessionInfo}->{OpenIDConnect_OP} = $self->{_oidcOPCurrent};
37 38
    $self->{sessionInfo}->{OpenIDConnect_access_token} =
      $self->{tmp}->{access_token};
39
    $self->{sessionInfo}->{OpenIDConnect_IDToken} = $self->{tmp}->{id_token};
40 41 42 43 44 45 46 47 48 49 50

    PE_OK;
}

## @apmethod int extractFormInfo()
# Does nothing
# @return Lemonldap::NG::Portal constant
sub extractFormInfo {
    my $self = shift;

    # Check callback
51
    my $callback_get_param = $self->{oidcRPCallbackGetParam};
52
    my $callback           = $self->param($callback_get_param);
53

54
    if ($callback) {
55 56 57 58 59 60 61 62 63 64

        $self->lmLog(
            "OpenIDConnect callback URI detected: "
              . $self->url( -path_info => 1, -query => 1 ),
            'debug'
        );

        # AuthN Response
        my $state = $self->param("state");

65 66 67 68 69 70 71 72 73 74
        # Restore state
        if ($state) {
            if ( $self->extractState($state) ) {
                $self->lmLog( "State $state extracted", 'debug' );
            }
            else {
                $self->lmLog( "Unable to extract state $state", 'error' );
                return PE_ERROR;
            }
        }
75

76 77 78 79 80 81 82 83 84 85
        # Get OpenID Provider
        my $op = $self->{_oidcOPCurrent};

        unless ($op) {
            $self->lmLog( "OpenID Provider not found", 'error' );
            return PE_ERROR;
        }

        $self->lmLog( "Using OpenID Provider $op", 'debug' );

86 87 88 89 90 91 92 93 94 95 96 97 98 99
        # Check error
        my $error = $self->param("error");
        if ($error) {
            my $error_description = $self->param("error_description");
            my $error_uri         = $self->param("error_uri");

            $self->lmLog( "Error returned by $op Provider: $error", 'error' );
            $self->lmLog( "Error description: $error_description",  'error' )
              if $error_description;
            $self->lmLog( "Error URI: $error_uri", 'error' ) if $error_uri;

            return PE_ERROR;
        }

100
        # Get access_token and id_token
101
        my $code = $self->param("code");
102 103 104
        my $auth_method =
          $self->{oidcOPMetaDataOptions}->{$op}
          ->{oidcOPMetaDataOptionsTokenEndpointAuthMethod};
105

106 107
        my $content =
          $self->getAuthorizationCodeAccessToken( $op, $code, $auth_method );
108 109
        return PE_ERROR unless $content;

110
        my $json = $self->decodeJSON($content);
111 112 113 114 115 116 117

        if ( $json->{error} ) {
            $self->lmLog( "Error in token response:" . $json->{error},
                'error' );
            return PE_ERROR;
        }

118 119 120 121 122
        # Check validity of token response
        unless ( $self->checkTokenResponseValidity($json) ) {
            $self->lmLog( "Token response is not valid", 'error' );
            return PE_ERROR;
        }
123 124 125
        else {
            $self->lmLog( "Token response is valid", 'debug' );
        }
126

127 128 129 130 131 132
        my $access_token = $json->{access_token};
        my $id_token     = $json->{id_token};

        $self->lmLog( "Access token: $access_token", 'debug' );
        $self->lmLog( "ID token: $id_token",         'debug' );

133
        # Verify JWT signature
134 135 136
        if ( $self->{oidcOPMetaDataOptions}->{$op}
            ->{oidcOPMetaDataOptionsCheckJWTSignature} )
        {
137
            unless ( $self->verifyJWTSignature( $id_token, $op ) ) {
138 139 140
                $self->lmLog( "JWT signature verification failed", 'error' );
                return PE_ERROR;
            }
141 142 143 144
            $self->lmLog( "JWT signature verified", 'debug' );
        }
        else {
            $self->lmLog( "JWT signature check disabled", 'debug' );
145
        }
146

Clément OUDOT's avatar
Clément OUDOT committed
147
        my $id_token_payload = $self->extractJWT($id_token)->[1];
148 149

        my $id_token_payload_hash =
150
          $self->decodeJSON( decode_base64($id_token_payload) );
151

152 153 154
        # Check validity of Access Token (optional)
        my $at_hash = $id_token_payload_hash->{'at_hash'};
        if ($at_hash) {
155
            unless ( $self->verifyHash( $access_token, $at_hash, $id_token ) ) {
156 157 158 159 160 161 162 163 164 165 166 167
                $self->lmLog( "Access token hash verification failed",
                    'error' );
                return PE_ERROR;
            }
            $self->lmLog( "Access token hash verified", 'debug' );
        }
        else {
            $self->lmLog(
                "No at_hash in ID Token, access token will not be verified",
                'debug' );
        }

168 169 170 171 172 173 174 175 176 177 178
        # Check validity of ID Token
        unless ( $self->checkIDTokenValidity( $op, $id_token_payload_hash ) ) {
            $self->lmLog( "ID Token not valid", 'error' );
            return PE_ERROR;
        }
        else {
            $self->lmLog( "ID Token is valid", 'debug' );
            $self->_dump($id_token_payload_hash);
        }

        # Get user id defined in 'sub' field
179 180 181 182
        my $user_id = $id_token_payload_hash->{sub};

        # Remember tokens
        $self->{tmp}->{access_token} = $access_token;
183
        $self->{tmp}->{id_token}     = $id_token;
184 185 186 187 188 189 190

        $self->lmLog( "Found user_id: " . $user_id, 'debug' );
        $self->{user} = $user_id;

        return PE_OK;
    }

191 192 193 194 195 196 197 198 199 200
    # No callback, choose Provider and send authn request
    my $op;

    unless ( $op = $self->param("idp") ) {
        $self->lmLog( "Redirecting user to OP list", 'debug' );

        # Control url parameter
        my $urlcheck = $self->controlUrlOrigin();
        return $urlcheck unless ( $urlcheck == PE_OK );

201 202 203 204 205 206
        # Auto select provider if there is only one
        my @oplist = sort keys %{ $self->{_oidcOPList} };

        if ( $#oplist == 0 ) {
            $op = shift @oplist;
            $self->lmLog( "Selecting the only defined OP: $op", 'debug' );
207 208
        }

209 210 211 212
        else {

            # IDP list
            my @list = ();
213 214 215 216 217

            my $portalPath = $self->{portal};
            $portalPath =~ s#^https?://[^/]+/?#/#;
            $portalPath =~ s#[^/]+\.pl$##;

218
            foreach (@oplist) {
219 220 221 222 223 224 225 226 227 228 229 230 231
                my $name = $self->{oidcOPMetaDataOptions}->{$_}
                  ->{oidcOPMetaDataOptionsDisplayName};
                my $icon = $self->{oidcOPMetaDataOptions}->{$_}
                  ->{oidcOPMetaDataOptionsIcon};
                my $img_src;

                if ($icon) {
                    $img_src =
                      ( $icon =~ m#^https?://# )
                      ? $icon
                      : $portalPath . "skins/common/" . $icon;
                }

232 233
                push @list,
                  {
234 235 236
                    val   => $_,
                    name  => $name,
                    icon  => $img_src,
237 238 239 240 241 242 243 244 245
                    class => "openidconnect",
                  };
            }
            $self->{list}            = \@list;
            $self->{confirmRemember} = 0;

            $self->{login} = 1;
            return PE_CONFIRM;
        }
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    }

    # Provider is choosen
    $self->lmLog( "OpenID Provider $op choosen", 'debug' );

    $self->{_oidcOPCurrent} = $op;

    # AuthN Request
    $self->lmLog( "Build OpenIDConnect AuthN Request", 'debug' );

    # Save state
    my $state = $self->storeState(qw/urldc checkLogins _oidcOPCurrent/);

    my $stateSession = $self->storeState();

    # Authorization Code Flow
    $self->{urldc} = $self->buildAuthorizationCodeAuthnRequest( $op, $state );

    $self->lmLog( "Redirect user to " . $self->{urldc}, 'debug' );

    return $self->_subProcess(qw(autoRedirect));

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    PE_OK;
}

## @apmethod int authenticate()
# Does nothing.
# @return Lemonldap::NG::Portal constant
sub authenticate {
    PE_OK;
}

## @apmethod int authFinish()
# Does nothing.
# @return Lemonldap::NG::Portal constant
sub authFinish {
    PE_OK;
}

## @apmethod int authLogout()
286
# Send request to endsession endpoint
287 288
# @return Lemonldap::NG::Portal constant
sub authLogout {
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    my $self = shift;

    my $op = $self->{sessionInfo}->{OpenIDConnect_OP};

    # Find endession endpoint
    my $endsession_endpoint =
      $self->{_oidcOPList}->{$op}->{conf}->{end_session_endpoint};

    if ($endsession_endpoint) {
        my $logout_url = $self->{portal} . "/?logout=1";
        my $logout_request =
          $self->buildLogoutRequest( $endsession_endpoint,
            $self->{sessionInfo}->{OpenIDConnect_IDToken}, $logout_url );

        $self->lmLog(
            "OpenID Connect logout to $op will be done on $logout_request",
            'debug' );

        $self->{urldc} = $logout_request;
    }
    else {
        $self->lmLog( "No end session endpoint found for $op", 'debug' );
    }

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    PE_OK;
}

## @apmethod boolean authForce()
# Does nothing
# @return result
sub authForce {
    return 0;
}

## @method string getDisplayType
# @return display type
sub getDisplayType {
    return "logo";
}

1;
__END__

=head1 NAME

=encoding utf8

Lemonldap::NG::Portal::AuthOpenIDConnect - Perl extension for building Lemonldap::NG
compatible portals with OpenID Connect.

=head1 SYNOPSIS

  use Lemonldap::NG::Portal::SharedConf;
  my $portal = new Lemonldap::NG::Portal::Simple(
         configStorage     => {...}, # See Lemonldap::NG::Portal
         authentication    => 'OpenIDConnect',
    );

  if($portal->process()) {
    # Write here the menu with CGI methods. This page is displayed ONLY IF
    # the user was not redirected here.
    print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
    print "...";

    # or redirect the user to the menu
    print $portal->redirect( -uri => 'https://portal/menu');
  }
  else {
    print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
    print "<html><body><h1>Unable to work</h1>";
    print "This server isn't well configured. Contact your administrator.";
    print "</body></html>";
  }

=head1 DESCRIPTION

OpenID Connect authentication module.

See L<Lemonldap::NG::Portal::Simple> for usage and other methods.

=head1 SEE ALSO

L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Portal::Simple>,
L<http://lemonldap-ng.org/>

=head1 AUTHOR

=over

=item Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>

=back

=head1 BUG REPORT

Use OW2 system to report bug or ask for features:
L<http://jira.ow2.org>

=head1 DOWNLOAD

Lemonldap::NG is available at
L<http://forge.objectweb.org/project/showfiles.php?group_id=274>

=head1 COPYRIGHT AND LICENSE

=over

=item Copyright (C) 2014 by Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>

=back

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see L<http://www.gnu.org/licenses/>.

=cut