Alternative (custom) Authentication HowTo

Intro

This page explains how to get Redmine to authenticate users against a different database. Perhaps you're running (and even wrote) an app that already stores account records, and you want Redmine to use those. Presumably that app doesn't support OpenID, else you'd be configuring that.

Having Redmine defer authentication to your other app is helpful to users--they only have to remember one set of passwords and the accounts can't get out-of-sync. And if they are registered with your main app, Redmine can be configured to automatically add them to its own table (without storing any password info) when they first log in there.

Redmine Support For Alternative Authentication

Redmine has specific support for alternative/custom authentication which makes implementing it very easy.
  • auth_sources table
    • You will add a record here specific to your custom authentication.
  • AuthSource class
    • You will create your own subclass of this, and implement the authenticate() method.
Redmine's authentication process is along these lines (LDAP & OpenID assumed to be disabled):
  1. First, try to authenticate login & password against Redmine's internal table (users).
  2. If that fails, try each alternative authentication source registered in the auth_sources table, stopping when one of the sources succeeds.
  3. If that fails, reject the login attempt.

Note: Redmine will make a note of which source successfully authenticated a specific user. That source will be tried first the next time that user tries to login. Administrators can manually set/override that on a user-by-user basis via Administration -> Users -> {user} -> Authentication mode.

Implementing An Alternative Authentication Source

This article assumes the alternative authentication involves querying a table (or tables) in some other database. However, the approach can be generalized to authenticate against pretty much anything else (some secret file, some network service, whatever fun scenario you have); you may want to examine the Redmine code in app/models/auth_source_ldap.rb for a non-database alternative authentication example.

Insert a Sensible auth_sources Record

First, we should decide what our auth_sources record will look like. Redmine core and our AuthSource subclass code will make use of that info, so it's good to figure this out up front.

For reference, here is the (Redmine 0.9) auth_sources table:

+-------------------+--------------+------+-----+---------+----------------+
| Field             | Type         | Null | Key | Default | Extra          |
+-------------------+--------------+------+-----+---------+----------------+
| id                | int(11)      | NO   | PRI | NULL    | auto_increment |
| type              | varchar(30)  | NO   |     |         |                |
| name              | varchar(60)  | NO   |     |         |                |
| host              | varchar(60)  | YES  |     | NULL    |                |
| port              | int(11)      | YES  |     | NULL    |                |
| account           | varchar(255) | YES  |     | NULL    |                |
| account_password  | varchar(60)  | YES  |     | NULL    |                |
| base_dn           | varchar(255) | YES  |     | NULL    |                |
| attr_login        | varchar(30)  | YES  |     | NULL    |                |
| attr_firstname    | varchar(30)  | YES  |     | NULL    |                |
| attr_lastname     | varchar(30)  | YES  |     | NULL    |                |
| attr_mail         | varchar(30)  | YES  |     | NULL    |                |
| onthefly_register | tinyint(1)   | NO   |     | 0       |                |
| tls               | tinyint(1)   | NO   |     | 0       |                |
+-------------------+--------------+------+-----+---------+----------------+
How our AuthSource subclass code will make use of these fields is more-or-less up to us, but there are two key constraints from Redmine:
  1. type must be the name of your AuthSource subclass
    • Redmine will use this field to instantiate your class and call its authenticate() method when attempting to authenticate a login attempt using your custom source.
    • This class name should begin with AuthSource.
    • We'll put "AuthSourceMyCustomApp"
  2. onthefly_register has a 1 or 0
    • Redmine will use this field to determine if unknown users (logins Redmine doesn't know about yet) can be registered within Redmine using this authentication source. Otherwise, if you put "0" here, an Administrator will first have to register the user manually (and presumably set their Authentication mode)--Redmine won't add them automatically.

Here's how we'll use these fields (substitute your own values):

Field Our Value Comment
id NULL Let the database engine provide the id.
type "AuthSourceMyCustomApp" Name of your AuthSource subclass
name "MyCustomApp" Name of this alternative authentication source. Will be displayed in Administration UI pages.
host "myApp.other.host.edu" Host name where the other database lives. This article doesn't assume that's the same host as where your Redmine database is.
port 3306 Port for the database on that other host.
account "myDbUser" Account name for accessing that other database.
account_password "myDbPass" Password for that account for accessing the other database.
base_dn "mysql:myApp"
attr_login "name" What field in your other database table contains the login?
attr_firstname "firstName" What field in your other database table contains the user's first name?
attr_lastname "lastName" What field in your other database table contains the user's last name?
attr_mail "email" What field in your other database table contains the user's email?
onthefly_register 1 Yes, if this source authenticates the user then Redmine should create an internal record for them (w/o password info).
tls 0 Dunno. 0 for "no".

Note: The attr_* fields are not always needed. They are used by the LDAP authentication source to map LDAP attributes to Redmine attributes. I recommend using them, however, since they make the authentication() code more widely applicable (fewer changes necessary for you to use the code in your specific situation).

So we insert the record into our Redmine's auth_sources table with SQL like the following:

1INSERT INTO auth_sources VALUES (NULL, 'AuthSourceGenboree', 'Genboree', 'myApp.other.host.edu', 3306, 'myDbUser', 'myDbPass', 'mysql:myApp', 'name', 'firstName', 'lastName', 'email', 1, 0)

Implement Your AuthSource Subclass

Create a new file for your AuthSource subclass in app/models/, following the naming scheme of the existing auth_source.rb and auth_source_ldap.rb.
  • Here we'll use app/models/auth_source_myApp.rb

Implement the class such that a call to its authenticate() method will contact the other database and use the table there to check the provided login credentials. The values in your auth_sources table record above are available via instances variables (e.g. self.host, self.base_dn, self.attr_firstname).

Here's our commented class:

  1# Redmine MyApp Authentication Source
  2#
  3# Copyright (C) 2010 Andrew R Jackson
  4#
  5# This program is free software; you can redistribute it and/or
  6# modify it under the terms of the GNU General Public License
  7# as published by the Free Software Foundation; either version 2
  8# of the License, or (at your option) any later version.
  9#
 10# This program is distributed in the hope that it will be useful,
 11# but WITHOUT ANY WARRANTY; without even the implied warranty of
 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13# GNU General Public License for more details.
 14#
 15# You should have received a copy of the GNU General Public License
 16# along with this program; if not, write to the Free Software
 17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 18
 19# Let's have a new class for our ActiveRecord-based connection
 20# to our alternative authentication database. Remember that we're
 21# not assuming that the alternative authentication database is on
 22# the same host (and/or port) as Redmine's database. So its current
 23# database connection may be of no use to us. ActiveRecord uses class
 24# variables to store state (yay) like current connections and such; thus,
 25# dedicated class...
 26class MyAppCustomDB_ActiveRecord < ActiveRecord::Base
 27  PAUSE_RETRIES = 5
 28  MAX_RETRIES = 50
 29end
 30
 31# Subclass AuthSource
 32class AuthSourceMyCustomApp < AuthSource
 33
 34  # authentication() implementation
 35  # - Redmine will call this method, passing the login and password entered
 36  #   on the Sign In form.
 37  #
 38  # +login+ : what user entered for their login
 39  # +password+ : what user entered for their password
 40  def authenticate(login, password)
 41    retVal = nil
 42    unless(login.blank? or password.blank?)
 43      # Get a connection to the authenticating database.
 44      # - Don't use ActiveRecord::Base when using establish_connection() to get at
 45      #   your alternative database (leave Redmine's current connection alone).
 46      #   Use class you prepped above.
 47      # - Recall that the values stored in the fields of your auth_sources
 48      #   record are available as self.fieldName
 49
 50      # First, get the DB Adapter name and database to use for connecting:
 51      adapter, dbName = self.base_dn.split(':')
 52
 53      # Second, try to get a connection, safely dealing with the MySQL<->ActiveRecord
 54      # failed connection bug that can still arise to this day (regardless of 
 55      # reconnect, oddly).
 56      retryCount = 0
 57      begin
 58        connPool = MyAppCustomDB_ActiveRecord.establish_connection(
 59          :adapter  => adapter,
 60          :host     => self.host,
 61          :port     => self.port,
 62          :username => self.account,
 63          :password => self.account_password,
 64          :database => dbName,
 65          :reconnect => true
 66        )
 67        db = connPool.checkout()
 68      rescue => err # for me, always due to dead connection; must retry bunch-o-times to get a good one if this happens
 69        if(retryCount < MyAppCustomDB_ActiveRecord::MAX_RETRIES)
 70          sleep(1) if(retryCount < MyAppCustomDB_ActiveRecord::PAUSE_RETRIES)
 71          retryCount += 1
 72          connPool.disconnect!
 73          retry # start again at begin
 74        else # too many retries, serious, reraise error and let it fall through as it normally would in Rails.
 75          raise
 76        end
 77      end
 78
 79      # Third, query the alternative authentication database for needed info. SQL
 80      # sufficient, obvious, and doesn't require other setup/LoC. Even more the
 81      # case if we have our database engine compute our digests (here, the whole
 82      # username is a salt). SQL also nice if your alt auth database doesn't have
 83      # AR classes and is not part of a Rails app, etc.
 84      resultRow = db.select_one(
 85        "SELECT #{self.attr_login}, #{self.attr_firstname}, #{self.attr_lastname}, #{self.attr_mail} " +
 86        "FROM genboreeuser " +
 87        "WHERE SHA1(CONCAT(#{self.attr_login}, password)) = SHA1(CONCAT('#{db.quote_string(login)}', '#{db.quote_string(password)}'))" 
 88      )
 89
 90      unless(resultRow.nil? or resultRow.empty?)
 91        user = resultRow[self.attr_login]
 92        unless(user.nil? or user.empty?)
 93          # Found a record whose login & password digest matches that computed
 94          # from Sign Inform parameters. If allowing Redmine to automatically
 95          # register such accounts in its internal table, return account
 96          # information to Redmine based on record found.
 97          retVal =
 98          [
 99            :firstname => resultRow[self.attr_firstname],
100            :lastname => resultRow[self.attr_lastname],
101            :mail => resultRow[self.attr_mail],
102            :auth_source_id => self.id
103          ] if(onthefly_register?)
104        end
105      end
106    end
107    # Check connection back into pool.
108    connPool.checkin(db)
109    return retVal
110  end
111
112  def auth_method_name
113    "MyCustomApp" 
114  end
115end
116

Deploy & Test

Save your new class in app/model/ and restart Redmine.

  • You ought to be able to try to log in as a use that exists in your alternative database but that doesn't exist in your Redmine instance.
  • Existing Redmine accounts (and passwords) should continue to work.
  • If you examine Redmine's users table, you should see records appear after each successful login that used your alternative database.
    • hashed_password will be empty for those records.
    • auth_source_id will have the id from auth_sources which worked to authenticate the user; NULL means "use internal Redmine authentication". The Administrator can also manually set this value via the Authentication mode UI widget I mentioned above.
  • Users authenticated with an alternative source will not be able to change their passwords using Redmine (great check by the core code) and will see an error message if they try to do so.

Follow-Up

If you want to ONLY use your alternative authentication source for Redmine Sign In, remove the "Register" button. We did this by removing the menu.push :register line in lib/redmine.rb. And we turned off the "Lost Password" feature via Administration -> Settings -> Authentication -> Lost password.

This was all pretty fast and simple to set up, thanks to how Redmine is organized and that some thought about permitting this kind of thing had been made. Quality. I hope I didn't get anything too wrong.

Bugs

  • In 1.0.1 if you got an error like "undefined method `stringify_keys!' for #<Array:...>) when logging" in see #6196
     1# Lines 97 from previous script
     2          retVal =
     3          {
     4            :firstname => resultRow[self.attr_firstname],
     5            :lastname => resultRow[self.attr_lastname],
     6            :mail => resultRow[self.attr_mail],
     7            :auth_source_id => self.id
     8          } if(onthefly_register?)
     9# ...