|
NAMECGI::Application::Plugin::Authentication - Authentication framework for CGI::ApplicationSYNOPSISpackage MyCGIApp; use base qw(CGI::Application); # make sure this occurs before you load the plugin use CGI::Application::Plugin::Authentication; MyCGIApp->authen->config( DRIVER => [ 'Generic', { user1 => '123' } ], ); MyCGIApp->authen->protected_runmodes('myrunmode'); sub myrunmode { my $self = shift; # The user should be logged in if we got here my $username = $self->authen->username; } DESCRIPTIONCGI::Application::Plugin::Authentication adds the ability to authenticate users in your CGI::Application modules. It imports one method called 'authen' into your CGI::Application module. Through the authen method you can call all the methods of the CGI::Application::Plugin::Authentication plugin.There are two main decisions that you need to make when using this module. How will the usernames and password be verified (i.e. from a database, LDAP, etc...), and how can we keep the knowledge that a user has already logged in persistent, so that they will not have to enter their credentials again on the next request (i.e. how do we 'Store' the authentication information across requests). Choosing a DriverThere are three drivers that are included with the distribution. Also, there is built in support for all of the Authen::Simple modules (search CPAN for Authen::Simple for more information). This should be enough to cover everyone's needs.If you need to authenticate against a source that is not provided, you can use the Generic driver which will accept either a hash of username/password pairs, or an array of arrays of credentials, or a subroutine reference that can verify the credentials. So through the Generic driver you should be able to write your own verification system. There is also a Dummy driver, which blindly accepts any credentials (useful for testing). See the CGI::Application::Plugin::Authentication::Driver::Generic, CGI::Application::Plugin::Authentication::Driver::DBI and, CGI::Application::Plugin::Authentication::Driver::Dummy docs for more information on how to use these drivers. And see the Authen::Simple suite of modules for information on those drivers. Choosing a StoreThe Store modules keep information about the authentication status of the user persistent across multiple requests. The information that is stored in the store include the username, and the expiry time of the login. There are two Store modules included with this distribution. A Session based store, and a Cookie based store. If your application is already using Sessions (through the CGI::Application::Plugin::Session module), then I would recommend that you use the Session store for authentication. If you are not using the Session plugin, then you can use the Cookie store. The Cookie store keeps all the authentication in a cookie, which contains a checksum to ensure that users can not change the information.If you do not specify which Store module you wish to use, the plugin will try to determine the best one for you. Login pageThe Authentication plugin comes with a default login page that can be used if you do not want to create a custom login page. This login form will automatically be used if you do not provide either a LOGIN_URL or LOGIN_RUNMODE parameter in the configuration. If you plan to create your own login page, I would recommend that you start with the HTML code for the default login page, so that your login page will contain the correct form fields and hidden fields.Ticket based authenticationThis Authentication plugin can handle ticket based authentication systems as well. All that is required of you is to write a Store module that can understand the contents of the ticket. The Authentication plugin will require at least the 'username' to be retrieved from the ticket. A Ticket based authentication scheme will not need a Driver module at all, since the actual verification of credentials is done by an external authentication system, possibly even on a different host. You will need to specify the location of the login page using the LOGIN_URL configuration variable, and unauthenticated users will automatically be redirected to your ticket authentication login page.EXPORTED METHODSauthenThis is the only method exported from this module. Everything is controlled through this method call, which will return a CGI::Application::Plugin::Authentication object, or just the class name if called as a class method. When using the plugin, you will always first call $self->authen or __PACKAGE__->authen and then the method you wish to invoke. For example:__PACKAGE__->authen->config( LOGIN_RUNMODE => 'login', ); - or - $self->authen->protected_runmodes(qw(one two)); METHODSconfigThis method is used to configure the CGI::Application::Plugin::Authentication module. It can be called as an object method, or as a class method. Calling this function, will not itself generate cookies or session ids.The following parameters are accepted:
Time values are specified in seconds. You can also specify the time by using a number with the following suffixes (m h d w), which represent minutes, hours, days and weeks. The default is 0 which means the login will never timeout. Note that the login is also dependent on the type of STORE that is used. If the Session store is used, and the session expires, then the login will also automatically expire. The same goes for the Cookie store. For backwards compatibility, if you set LOGIN_SESSION_TIMEOUT to a time value instead of a hashref, it will be treated as an IDLE_FOR time out. # force re-authentication if idle for more than 15 minutes LOGIN_SESSION_TIMEOUT => '15m' # Everyone must re-authentication if idle for more than 30 minutes # also, everyone must re-authentication at least once a day # and root must re-authentication if idle for more than 5 minutes LOGIN_SESSION_TIMEOUT => { IDLE_FOR => '30m', EVERY => '1d', CUSTOM => sub { my $authen = shift; return ($authen->username eq 'root' && (time() - $authen->last_access) > 300) ? 1 : 0; } }
protected_runmodesThis method takes a list of runmodes that are to be protected by authentication. If a user tries to access one of these runmodes, then they will be redirected to a login page unless they are properly logged in. The runmode names can be a list of simple strings, regular expressions, or special directives that start with a colon. This method is cumulative, so if it is called multiple times, the new values are added to existing entries. It returns a list of all entries that have been saved so far. Calling this function, will not itself generate cookies or session ids.
# match all runmodes __PACKAGE__->authen->protected_runmodes(':all'); # only protect runmodes one two and three __PACKAGE__->authen->protected_runmodes(qw(one two three)); # protect only runmodes that start with auth_ __PACKAGE__->authen->protected_runmodes(qr/^auth_/); # protect all runmodes that *do not* start with public_ __PACKAGE__->authen->protected_runmodes(qr/^(?!public_)/); is_protected_runmodeThis method accepts the name of a runmode, and will tell you if that runmode is a protected runmode (i.e. does a user need to be authenticated to access this runmode). Calling this function, will not itself generate cookies or session ids.redirect_after_loginThis method is be called during the prerun stage to redirect the user to the page that has been configured as the destination after a successful login. The location is determined as follows:
redirect_to_loginThis method is be called during the prerun stage if the current user is not logged in, and they are trying to access a protected runmode. It will redirect to the page that has been configured as the login page, based on the value of LOGIN_RUNMODE or LOGIN_URL If nothing is configured a simple login page will be automatically provided.redirect_to_logoutThis method is called during the prerun stage if the user has requested to be logged out. It will redirect to the page that has been configured as the logout page, based on the value of LOGOUT_RUNMODE or LOGOUT_URL If nothing is configured, the page will redirect to the website homepage.setup_runmodesThis method is called during the prerun stage to register some custom runmodes that the Authentication plugin requires in order to function. Calling this function, will not itself generate cookies or session ids.last_loginThis will return return the time of the last login for this usermy $last_login = $self->authen->last_login; This function will initiate a session or cookie if one has not been created already. last_accessThis will return return the time of the last access for this usermy $last_access = $self->authen->last_access; This function will initiate a session or cookie if one has not been created already. is_login_timeoutThis will return true or false depending on whether the users login status just timed out$self->add_message('login session timed out') if $self->authen->is_login_timeout; This function will initiate a session or cookie if one has not been created already. is_authenticatedThis will return true or false depending on the login status of this userassert($self->authen->is_authenticated); # The user should be logged in if we got here This function will initiate a session or cookie if one has not been created already. login_attemptsThis method will return the number of failed login attempts have been made by this user since the last successful login. This is not a number that can be trusted, as it is dependent on the underlying store to be able to return the correct value for this user. For example, if the store uses a cookie based session, the user trying to login could delete their cookies, and hence get a new session which will not have any login attempts listed. The number will be cleared upon a successful login. This function will initiate a session or cookie if one has not been created already.usernameThis will return the username of the currently logged in user, or undef if no user is currently logged in.my $username = $self->authen->username; This function will initiate a session or cookie if one has not been created already. is_new_loginThis will return true or false depending on if this is a fresh login$self->log->info("New Login") if $self->authen->is_new_login; This function will initiate a session or cookie if one has not been created already. credentialsThis method will return the names of the form parameters that will be looked for during a login. By default they are authen_username and authen_password, but these values can be changed by supplying the CREDENTIALS parameters in the configuration. Calling this function, will not itself generate cookies or session ids.logoutThis will attempt to logout the user. If during a request the Authentication module sees a parameter called 'authen_logout', it will automatically call this method to log out the user.$self->authen->logout(); This function will initiate a session or cookie if one has not been created already. driversThis method will return a list of driver objects that are used for verifying the login credentials. Calling this function, will not itself generate cookies or session ids.storeThis method will return a store object that is used to store information about the status of the authentication across multiple requests. This function will initiate a session or cookie if one has not been created already.initializeThis does most of the heavy lifting for the Authentication plugin. It will check to see if the user is currently attempting to login by looking for the credential form fields in the query object. It will load the required driver objects and authenticate the user. It is OK to call this method multiple times as it checks to see if it has already been executed and will just return without doing anything if called multiple times. This allows us to call initialize as late as possible in the request so that no unnecessary work is done.The user will be logged out by calling the "logout()" method if the login session has been idle for too long, if it has been too long since the last login, or if the login has timed out. If you need to know if a user was logged out because of a time out, you can call the "is_login_timeout" method. If all goes well, a true value will be returned, although it is usually not necessary to check. This function will initiate a session or cookie if one has not been created already. displayThis method will return the CGI::Application::Plugin::Authentication::Display object, creating and caching it if necessary.login_boxThis method will return the HTML for a login box that can be embedded into another page. This is the same login box that is used in the default authen_login runmode that the plugin provides.This function will initiate a session or cookie if one has not been created already. newThis method creates a new CGI::Application::Plugin::Authentication object. It requires as it's only parameter a CGI::Application object. This method should never be called directly, since the 'authen' method that is imported into the CGI::Application module will take care of creating the CGI::Application::Plugin::Authentication object when it is required. Calling this function, will not itself generate cookies or session ids.instanceThis method works the same way as 'new', except that it returns the same Authentication object for the duration of the request. This method should never be called directly, since the 'authen' method that is imported into the CGI::Application module will take care of creating the CGI::Application::Plugin::Authentication object when it is required. Calling this function, will not itself generate cookies or session ids.CGI::Application CALLBACKSprerun_callbackThis method is a CGI::Application prerun callback that will be automatically registered for you if you are using CGI::Application 4.0 or greater. If you are using an older version of CGI::Application you will have to create your own cgiapp_prerun method and make sure you call this method from there.sub cgiapp_prerun { my $self = shift; $self->CGI::Application::Plugin::Authentication::prerun_callback(); } CGI::Application RUNMODESauthen_login_runmodeThis runmode is provided if you do not want to create your own login runmode. It will display a simple login form for the user, which can be replaced by assigning RENDER_LOGIN a coderef that returns the HTML.authen_dummy_redirectThis runmode is provided for convenience when an external redirect needs to be done. It just returns an empty string.EXAMPLEIn a CGI::Application module:use base qw(CGI::Application); use CGI::Application::Plugin::AutoRunmode; use CGI::Application::Plugin::Session; use CGI::Application::Plugin::Authentication; __PACKAGE__->authen->config( DRIVER => [ 'Generic', { user1 => '123' } ], STORE => 'Session', LOGOUT_RUNMODE => 'start', ); __PACKAGE__->authen->protected_runmodes(qr/^auth_/, 'one'); sub start : RunMode { my $self = shift; } sub one : RunMode { my $self = shift; # The user will only get here if they are logged in } sub auth_two : RunMode { my $self = shift; # This is also protected because of the # regexp call to protected_runmodes above } COMPATIBILITY WITH CGI::Application::Plugin::ActionDispatchThe prerun callback has been modified so that it will check for the presence of a prerun mode. This is for compatibility with CGI::Application::Plugin::ActionDispatch. This change should be considered experimental. It is necessary to load the ActionDispatch module so that the two prerun callbacks will be called in the correct order.RECOMMENDED USAGE
TODOThere are lots of things that can still be done to improve this plugin. If anyone else is interested in helping out feel free to dig right in. Many of these things don't need my input, but if you want to avoid duplicated efforts, send me a note, and I'll let you know of anyone else is working in the same area.
BUGSThis is alpha software and as such, the features and interface are subject to change. So please check the Changes file when upgrading.Some of the test scripts appear to be incompatible with versions of Devel::Cover later than 0.65. SEE ALSOCGI::Application, perl(1)AUTHORAuthor: Cees Hek <ceeshek@gmail.com>; Co-maintainer: Nicholas Bamber <nicholas@periapt.co.uk>.CREDITSThanks to SiteSuite <http://www.sitesuite.com.au> for funding the development of this plugin and for releasing it to the world.Thanks to Christian Walde for suggesting changes to fix the incompatibility with CGI::Application::Plugin::ActionDispatch and for help with github. Thanks to Alexandr Ciornii for pointing out some typos. LICENCE AND COPYRIGHTCopyright (c) 2005, SiteSuite. All rights reserved. Copyright (c) 2010, Nicholas Bamber. (Portions of the code).This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The background images in the default login forms are used courtesy of www.famfamfam.com <http://www.famfamfam.com/lab/icons/silk/>. Those icons are issued under the Creative Commons Attribution 3.0 License <http://creativecommons.org/licenses/by/3.0/>. Those icons are copyrighted 2006 by Mark James <mjames at gmail dot com> DISCLAIMER OF WARRANTYBECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Visit the GSP FreeBSD Man Page Interface. |