Project

General

Profile

Alternativecustom authentication HowTo » History » Version 7

Glen Vanderhel, 2012-10-28 11:49
Spelling mistake - Jooma>>Joomla

1 1 Andrew R Jackson
h1. Alternative (custom) Authentication HowTo
2
3
h2. Intro
4
5
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.
6
7
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.
8
9
h2. Redmine Support For Alternative Authentication
10
11
Redmine has specific support for alternative/custom authentication which makes implementing it very easy.
12
* +@auth_sources@ table+
13
** You will add a record here specific to your custom authentication.
14
* +@AuthSource@ class+
15
** You will create your own subclass of this, and implement the @authenticate()@ method.
16
17
Redmine's authentication process is along these lines (LDAP & OpenID assumed to be disabled):
18
# First, try to authenticate @login@ & @password@ against Redmine's internal table (@users@).
19
# If that fails, try each alternative authentication source registered in the @auth_sources@ table, stopping when one of the sources succeeds.
20
# If that fails, reject the login attempt.
21
22
_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@._
23
24
h2. Implementing An Alternative Authentication Source
25
26
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.
27
28
h3. Insert a Sensible @auth_sources@ Record
29
30
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.
31
32 2 Eric Davis
For reference, here is the (Redmine 0.9) @auth_sources@ table:
33 1 Andrew R Jackson
34
<pre>
35
+-------------------+--------------+------+-----+---------+----------------+
36
| Field             | Type         | Null | Key | Default | Extra          |
37
+-------------------+--------------+------+-----+---------+----------------+
38
| id                | int(11)      | NO   | PRI | NULL    | auto_increment |
39
| type              | varchar(30)  | NO   |     |         |                |
40
| name              | varchar(60)  | NO   |     |         |                |
41
| host              | varchar(60)  | YES  |     | NULL    |                |
42
| port              | int(11)      | YES  |     | NULL    |                |
43
| account           | varchar(255) | YES  |     | NULL    |                |
44
| account_password  | varchar(60)  | YES  |     | NULL    |                |
45
| base_dn           | varchar(255) | YES  |     | NULL    |                |
46
| attr_login        | varchar(30)  | YES  |     | NULL    |                |
47
| attr_firstname    | varchar(30)  | YES  |     | NULL    |                |
48
| attr_lastname     | varchar(30)  | YES  |     | NULL    |                |
49
| attr_mail         | varchar(30)  | YES  |     | NULL    |                |
50
| onthefly_register | tinyint(1)   | NO   |     | 0       |                |
51
| tls               | tinyint(1)   | NO   |     | 0       |                |
52
+-------------------+--------------+------+-----+---------+----------------+
53
</pre>
54
55
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:
56
# +@type@ must be the name of your @AuthSource@ subclass+
57
#* 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.
58
#* This class name should begin with @AuthSource@.
59
#* We'll put "@AuthSourceMyCustomApp@"
60
# +@onthefly_register has a 1 or 0@+
61
#* 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.
62
63
Here's how we'll use these fields (substitute your own values):
64
65
| *Field* | *Our Value* | *Comment* |
66
| id | @NULL@ | Let the database engine provide the id. |
67
| type | "AuthSourceMyCustomApp" | Name of your @AuthSource@ subclass |
68
| name | "MyCustomApp" | Name of this alternative authentication source. Will be displayed in Administration UI pages.|
69
| 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. |
70
| port | 3306 | Port for the database on that other host. |
71
| account | "myDbUser" | Account name for accessing that other database. |
72
| account_password | "myDbPass" | Password for that account for accessing the other database. |
73
| base_dn | "mysql:myApp" | This field sounds very LDAP-ish. Sorry. We will interpret it to mean "BASic Database Name data" and store within a string of the form "@{dbAdapterName}:{dbName}@".
74
| attr_login | "name" | What field in your other database table contains the login? |
75
| attr_firstname | "firstName" | What field in your other database table contains the user's first name? |
76
| attr_lastname | "lastName" | What field in your other database table contains the user's last name? |
77
| attr_mail | "email" | What field in your other database table contains the user's email? |
78
| onthefly_register | 1 | Yes, if this source authenticates the user then Redmine should create an internal record for them (w/o password info). |
79
| tls | 0 | Dunno. 0 for "no". |
80
81 3 Eric Davis
_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)._
82 1 Andrew R Jackson
83
So we insert the record into our Redmine's @auth_sources@ table with SQL like the following:
84
85
<pre>
86
<code class="Sql">
87
INSERT INTO auth_sources VALUES (NULL, 'AuthSourceGenboree', 'Genboree', 'myApp.other.host.edu', 3306, 'myDbUser', 'myDbPass', 'mysql:myApp', 'name', 'firstName', 'lastName', 'email', 1, 0)
88
</code>
89
</pre>
90
91
h3. Implement Your @AuthSource@ Subclass
92
93
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@.
94
* Here we'll use @app/models/auth_source_myApp.rb@
95
96
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@). 
97
98
Here's our commented class:
99
100
<pre>
101
<code class="ruby">
102
# Redmine MyApp Authentication Source
103
#
104
# Copyright (C) 2010 Andrew R Jackson
105
#
106
# This program is free software; you can redistribute it and/or
107
# modify it under the terms of the GNU General Public License
108
# as published by the Free Software Foundation; either version 2
109
# of the License, or (at your option) any later version.
110
#
111
# This program is distributed in the hope that it will be useful,
112
# but WITHOUT ANY WARRANTY; without even the implied warranty of
113
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
114
# GNU General Public License for more details.
115
#
116
# You should have received a copy of the GNU General Public License
117
# along with this program; if not, write to the Free Software
118
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
119
120
# Let's have a new class for our ActiveRecord-based connection
121
# to our alternative authentication database. Remember that we're
122
# not assuming that the alternative authentication database is on
123
# the same host (and/or port) as Redmine's database. So its current
124
# database connection may be of no use to us. ActiveRecord uses class
125
# variables to store state (yay) like current connections and such; thus,
126
# dedicated class...
127
class MyAppCustomDB_ActiveRecord < ActiveRecord::Base
128
  PAUSE_RETRIES = 5
129
  MAX_RETRIES = 50
130
end
131
132
# Subclass AuthSource
133
class AuthSourceMyCustomApp < AuthSource
134
135
  # authentication() implementation
136
  # - Redmine will call this method, passing the login and password entered
137
  #   on the Sign In form.
138
  #
139
  # +login+ : what user entered for their login
140
  # +password+ : what user entered for their password
141
  def authenticate(login, password)
142
    retVal = nil
143
    unless(login.blank? or password.blank?)
144
      # Get a connection to the authenticating database.
145
      # - Don't use ActiveRecord::Base when using establish_connection() to get at
146
      #   your alternative database (leave Redmine's current connection alone).
147
      #   Use class you prepped above.
148
      # - Recall that the values stored in the fields of your auth_sources
149
      #   record are available as self.fieldName
150
151
      # First, get the DB Adapter name and database to use for connecting:
152
      adapter, dbName = self.base_dn.split(':')
153
154
      # Second, try to get a connection, safely dealing with the MySQL<->ActiveRecord
155
      # failed connection bug that can still arise to this day (regardless of 
156
      # reconnect, oddly).
157
      retryCount = 0
158
      begin
159
        connPool = MyAppCustomDB_ActiveRecord.establish_connection(
160
          :adapter  => adapter,
161
          :host     => self.host,
162
          :port     => self.port,
163
          :username => self.account,
164
          :password => self.account_password,
165
          :database => dbName,
166
          :reconnect => true
167
        )
168
        db = connPool.checkout()
169
      rescue => err # for me, always due to dead connection; must retry bunch-o-times to get a good one if this happens
170
        if(retryCount < MyAppCustomDB_ActiveRecord::MAX_RETRIES)
171
          sleep(1) if(retryCount < MyAppCustomDB_ActiveRecord::PAUSE_RETRIES)
172
          retryCount += 1
173
          connPool.disconnect!
174
          retry # start again at begin
175
        else # too many retries, serious, reraise error and let it fall through as it normally would in Rails.
176
          raise
177
        end
178
      end
179
180
      # Third, query the alternative authentication database for needed info. SQL
181
      # sufficient, obvious, and doesn't require other setup/LoC. Even more the
182
      # case if we have our database engine compute our digests (here, the whole
183
      # username is a salt). SQL also nice if your alt auth database doesn't have
184
      # AR classes and is not part of a Rails app, etc.
185
      resultRow = db.select_one(
186
        "SELECT #{self.attr_login}, #{self.attr_firstname}, #{self.attr_lastname}, #{self.attr_mail} " +
187
        "FROM genboreeuser " +
188
        "WHERE SHA1(CONCAT(#{self.attr_login}, password)) = SHA1(CONCAT('#{db.quote_string(login)}', '#{db.quote_string(password)}'))"
189
      )
190
191
      unless(resultRow.nil? or resultRow.empty?)
192
        user = resultRow[self.attr_login]
193
        unless(user.nil? or user.empty?)
194
          # Found a record whose login & password digest matches that computed
195
          # from Sign Inform parameters. If allowing Redmine to automatically
196
          # register such accounts in its internal table, return account
197
          # information to Redmine based on record found.
198
          retVal =
199 6 Anibal Sanchez
          {
200 1 Andrew R Jackson
            :firstname => resultRow[self.attr_firstname],
201
            :lastname => resultRow[self.attr_lastname],
202
            :mail => resultRow[self.attr_mail],
203
            :auth_source_id => self.id
204 6 Anibal Sanchez
          } if(onthefly_register?)
205 1 Andrew R Jackson
        end
206
      end
207
    end
208
    # Check connection back into pool.
209
    connPool.checkin(db)
210
    return retVal
211
  end
212
213
  def auth_method_name
214
    "MyCustomApp"
215
  end
216
end
217
218
</code>
219
</pre>
220
221
h2. Deploy & Test
222
223
Save your new class in @app/model/@ and restart Redmine.
224
225
* 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.
226
* Existing Redmine accounts (and passwords) should continue to work.
227
* If you examine Redmine's @users@ table, you should see records appear after each successful login that used your alternative database.
228
** @hashed_password@ will be empty for those records.
229
** @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.
230
* 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.
231
232
h2. Follow-Up
233
234
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@.
235
236 4 Paco Alcaide
<pre>
237 1 Andrew R Jackson
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.
238
</pre>
239
240 6 Anibal Sanchez
h2. Joomla
241
242 7 Glen Vanderhel
We've customized the code to integrate Redmine with Joomla. Please, check the attachment to review an implementation for Joomla 2.5 and Redmine 2.0.3.
243 6 Anibal Sanchez
244
As Joomla does not have lastname in the users table, we have added a Html tag to show an icon in Redmine.
245
246
Remember to change the DB prefix (line 84) and the lastname customization (line 98).
247
248 5 Julien Recurt
h2. Bugs
249
250
 * In 1.0.1 if you got an error like "undefined method `stringify_keys!' for #<Array:...>) when logging" in see #6196
251
<pre>
252
<code class="ruby">
253
# Lines 97 from previous script
254
          retVal =
255
          {
256
            :firstname => resultRow[self.attr_firstname],
257
            :lastname => resultRow[self.attr_lastname],
258
            :mail => resultRow[self.attr_mail],
259
            :auth_source_id => self.id
260
          } if(onthefly_register?)
261
# ...
262 1 Andrew R Jackson
</code>
263
</pre>
264 6 Anibal Sanchez
265
 * In 2.0.3, the codefix for #6196 is still required, we've fixed the original code.