Tutorial: Authlogic Basic Setup

Please note this tutorial has been moved to the README in the authlogic_example respository. This tutorial is stored with the example app incase you are more of a hands on learner, you can play around with the resulting code.

  • Share/Save/Bookmark

65 Responses to “Tutorial: Authlogic Basic Setup”

  1. okr says:

    Thank you for this tutorial, authlogic looks like a breath of fresh air in rails authentication. I think I am definitely going to try using it on my next project but I usually need some sort of role based authentication for most of my projects. Is there any chance you could cover role integration or how to setup a basic admin user type in a separate tutorial? Maybe I missed something in the documentation?

  2. Ben Johnson says:

    okr, roles are really a permissions system that is separate from authentication. The problem with roles is that it depends on the app. Some apps might need very granular roles, others might need some more broad / simple. There are a lot of solutions on this and I view this as a completely separate project. Lastly, depending on the type of role system you need the implementation is different. So lumping this in with Authlogic doesn’t really make sense. I have both of the rails recipes books, and one of the has a great tutorial on this. You should check it out.

    Secondly, setting up a basic admin area is easy. Check out this screencast: http://www.vimeo.com/637894 . I think that is a great tutorial on how to set up an admin area using the REST development style. The screen cast uses resource_controller. You don’t *have* to use this, but it does help DRY up those repetitive admin controllers.

    Hope this helps.

  3. Ben Johnson says:

    okr, you might also want to check out: http://railscasts.com/episodes/19-where-administration-goes

  4. Evan says:

    Step 4 comes before step 3? lol

  5. Ben Johnson says:

    Yes, you also need to do the first step last. (I fixed the typo)

  6. vince says:

    Any chance for a tutorial on how to migrate from Restful Authentication to Auth logic?

  7. Tim S says:

    Has anyone interfaced this with DocSavage’s rails-authorization-plugin? Cursorily, it looks like they’ll play nice together, but I’d love some verification before I go ahead and try it for myself. :-)

    FTR, I prefered "authgasm".

  8. Ben Johnson says:

    Vince, I have that in my queue of articles to write. I recently converted 3 of my apps from restful_authentication to Authlogic, and it was pretty simple. Mainly removing a lot of code.

    Tim, I like Authgasm too, but the suits dont. I have not played around with the rails-authorization-plugin enough to answer this question properly. If you decide to mess around with it, let me know how it goes.

  9. okr says:

    I just wanted to say in one day I got authlogic working with a namespaced admin area and some simple roles I built in and it works like a charm. Thank you for making such an easy to use authorization system. Now I just need to get my "forgot password" action working.

  10. Spyou says:

    Thank for this plugin, awesome solution for a simple login.

    I’ll use it as a base on my future Twitter Mashup.

    Thank you very much.

  11. Aneem says:

    Authologic will be nice when I get more built in features like below.

    http://github.com/ariejan/baseapp/tree/master looks promising to me. It has all features (open id, roles, user administration, restful auth etc.) built in. Plus some template features.

  12. Peter Zingg says:

    I just did a personal review of 8 or 9 starter apps as well as a summary of the gems and plugins currently on display at the Rails Rumble 2008 site. I am so happy to find authlogic. Here are the pieces I think I am going to pull from these projects:

    authentication layer – authlogic
    configatron, roles, user adminstration and profile editing, forgot password – baseapp
    multiple openid identities (and idselector.com ui) – embark
    send user his lost (decrptyed) password – insoshi
    quick and dirty forms – awesome_fields and better_partials

    If I get it where I want it today, I’ll put it into github.

  13. Stefan Weber says:

    Thank you very much for this plugin. Also iam totally fresh to Ruby and Ruby on Rails it is very easy to use and (thanks to your blog here) i understand whats going on ;-)

  14. TW Scannell says:

    This looks great.
    I haven’t been able to install yet as I get an error:

    ERROR: Error installing authlogic:
    echoe requires RubyGems version >= 1.2

    I finally found this and it seemed to work.

    script/plugin install git://github.com/binarylogic/authlogic.git

  15. Ben Johnson says:

    Yeah, rails gem support requires echoe. I will more than likely either switch to Hoe or require echoe as a dependency.

  16. Hey Ben,

    Thanks so much for your efforts. Just came across this today on the recommendation from a friend last night. I was going through this tutorial and noticed that your user model spec in this tutorial isn’t complete. You’re missing the persistence_token. Might want to sync that up with your README in the gem.

    Thanks again.

  17. akahn says:

    Thanks for this. I’m very new to Rails and I’m going to be using this for my first app. So far it seems simpler and easier than restful_authentication. One thing I’d like to point out is that the views in your sample app on github don’t work with the code here in this tutorial. E.g. _form.html.erb takes openid information and an email address, when that isn’t in the model created in this tutorial.

  18. Ben Johnson says:

    Hey Michael, thanks for the heads up on this, I changed it. But it really doesn’t matter, you could call the field that and authlogic will adjust accordingly and work just fine. It does some "smart checking" for common field names.

    Akahn, yeah I had a feeling that might be a problem. I will put some notes in the views. It should be fairly obvious that there is OpenID support in the app. Simply removing the OpenID code would make the app work just fine.

  19. Hello Ben,

    great jog with Authlogic.

    I was testing the plugin and it seems to work perfectly using this tutorial, but when I tried using it inside a namespace like Security::User and Security::UserSession, I had the following error:

    undefined local variable or method `user’ for Security::UserSession:Class

    The stack trace sent me to:

    vendor/plugins/authlogic/lib/authlogic/session/base.rb:359:in `create_configurable_methods!’

    So I took a look there and found this line

    alias_method :#{klass_name.underscore}, :record

    I figured out the problem might be the klass_name.underscore, so I tried changing it to:

    alias_method :#{klass_name.underscore.tr(’/',’_')}, :record

    And it worked.

    I was wondering if I should create a ticket at lighthouse, because it seems a little bug.

  20. Ron Damen says:

    Excellent plugin! Just went through the tutorial and imho it’s nicer than anything else out there at the moment.

    That said, just starting out with Rspec I’m having trouble writing specs for the users controller and controllers that require authentication.

    If anyone could share some examples I’d appreciate it.

  21. Ron Damen says:

    I’ve made some progress on writing specs and forked the example app on Github for anyone interested and to hopefully receive some feedback.


    If you see anything that’s just plain wrong or could be improved please fork or leave a comment.

  22. James Lavin says:

    Hi, Ben:

    Your plugin looked interesting enough for me to rip out restful_authentication and give it a try. But I want to repeat Tim S’s question because (unless I made a mistake, which is possible) it doesn’t seem to work out of the box with rails-authorization-plugin. That’s a very popular plugin, so it would be great if they worked together without custom code.

    http://github.com/DocSavage/rails-authorization-plugin/tree/master says, "make sure your application provides a current_user method or something that returns the current user object (resful_authentication provides this out of the box)."

    Authlogic does provide a current_user method, but the authorization plugin can’t seem to use it. It keeps giving me the following error message:

    Authorization::CannotObtainUserObject (Couldn’t find #current_user or @user, and nothing appropriate found in hash):
    /vendor/plugins/rails-authorization-plugin/lib/authorization.rb:117:in `get_user’
    /vendor/plugins/rails-authorization-plugin/lib/authorization.rb:74:in `has_permission?’

    Did I misconfigure Authlogic? If not, what would be your official recommendation for getting these two plugins to talk with each other? I don’t want to put in my own hack and then get screwed up later when Authlogic changes.


    James Lavin

  23. Joel Margolese says:

    Is there a way to do email confirmations for new accounts? (I know I can add it, just wondering if it’s builtin and/or documented somewhere?)

    Also any anti-bot technologies like CAPTIAs?

    Looks great!


  24. David says:

    Sort of annoyed. It took me an hour to find out I needed to install Git.

    Could you point things out to noobies like me in the future? Would take two lines of text.


  25. James B. Byrne says:

    I ran across a reference to this on the RSpec mailing list and am giving it a tryout. On first blush I am favourably impressed with the entire approach, taking the application coding out of the hands of generators while providing the background functionality necessary.

    The references to the view code present in the git repository may cause recent users of this tutorial some difficulty however. That code is now polluted with the changes introduced in the later tutorials OpenID and ResttingPasswords. If you do not wish to reproduce the original view code in line in this article then perhaps a different resource reference with the pristine versions might be provided instead?

  26. Ben Johnson says:

    Hi everyone, I apologize for taking a few days for a response, this has been an unusually busy week for me. Anyways, here are my replies:

    Carlos, great find, I went ahead and fixed this, just update your gem.

    James Lavin, the current_user method is just a method you create yourself. Maybe you forgot to do helper_method :current_user? Anyways, I’ll install the authorization plugin and see what the deal is. Regardless, it should work because the current_user method is no different than the restful_auth one in terms of the value it returns.

    Joel, that’s really up to you. Authlogic doesn’t have this built in, but if gives you some helpful tools. Take a look at the resetting password tutorial. You can use the same things I use in there to confirm accounts, such as the perishable_token, etc.

    David, I will add that in, I didn’t really think about mentioning it since the plugin url begins with git://, but I’ll put something in here mentioning git is required.

    James Byrne, I will more than likely just create a branch for each tutorial and clean up the code respectively.

  27. Jan says:

    This seems to be a great plugin/gem. But beware of a return statement in the block after the "@user_session.save". I wanted to do a simple "render :text => ’success’ and return" as a temporary workaround but this skips the after_save filter(s) and thus persisting the session.
    Another issue is the ability to use authlogic in cocumber tests. I’m unable to stay logged in during a scenario.

  28. Ivan says:

    why not use

    def current_user
    @current_user ||= current_user_session && current_user_session.user

    instead of

    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.user

    and alike for current_user_session

  29. Ivan says:

    me again
    in documentation there is login_field_validates_confirmation_of_options instead of password_field_validates_confirmation_of_options

  30. Ben Johnson says:

    Thanks jan, I will look into that.

    Ivan, because if a current user is not found it will return nil, which means it will keep executing that code. You only want that statement executed once.

  31. Keith says:

    Hi, my problem is that I don’t want the user to be automatically logged-in. When a user is created I can see that the cookies are set. How do i prevent it?

  32. Keith says:

    Nevermind my comment. Found out about session_ids => []

  33. Lee says:

    First off, I’ve been playing around with authlogic and I really like it so far. I appreciate your work Ben.

    One question though…say I want to load that flash message with user details (say, login, last_login_at, and last_login_ip) on successful creation of a user_session. At what point do I have access to "current_user"? Can I simply call current_user.last_login_at inside the create method of UserSessionsController to build my flash message text? Thanks for any suggestions.

  34. Ben Johnson says:

    Lee, I don’t see any reason why you wouldn’t be able to. Try it out, keep in mind you are in control of the current_user method, so if it doesnt work because of caching (that first line: return @current_user if defined?(@current_user)), try clearing out the @current_user variable so it will try and find the user again. But I don’t see any reason why it wouldn’t work without doing this.

  35. Lee says:

    Yeah, I commented out the ‘return @current_user if defined?(@current_user)’ to see if that worked but no cigar…@current_use is still null, even after forcing it like that.

  36. Hi Ben,

    If i wanted to maintain extra information within the session how can i do that?
    My first instinct would be to create attr_accessor in the UserSession class, let the login form capture it from the user and then let the @user_session.save take care of storing it. Is this correct?
    I tried it but didnt seem to work, can you please point me in the right direction?
    (I’ve got a financial app and i’d like the user to select the financial year when they log in.)


  37. Niko says:

    Thanks a lot for this gem (pun inteded :)!

    I came across a small issue with the magic timestamping. I think authlogic should respect the ActiveRecord default timezone or have an own option for the timezone (or both). Something like:

    record.current_login_at = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now

    in session/base.rb:278 #save.

    Please keep up the great work, kind regards, Niko.

  38. Arik Jones says:

    Would it be possible to show some working examples of how to scope users to an account model using the methods provided by authlogic?


  39. dan says:

    Hi Ben,

    Thanks for putting this gem together. I successfully installed the gem, but I’m having trouble getting this tutorial running on my current setup (Rails 2.0.2, InstantRails, Apache). I started again with a blank test app to see if that would work, but no luck.

    I keep getting the error ‘uninitialized constant Authlogic’ (NameError in User sessionsController#new ). I think this may be because ‘config.gem’ is not supported until Rails 2.1. Does this gem work with Rails 2.0.2, or if other people have had this problem? Any thoughts?


  40. Nice tutorial & terrific plugin!

    Thanks for all!

  41. Jay says:

    Has anyone tried using authlogic with the role_requirement plugin? Ben, are there any roles plugins that you recommend in particular, to avoid having to roll our own?


  42. Ed says:

    Hi, just wanted to register my interest in Jay’s question: Wat role authorization plugins work easiest with authlogic?

  43. Niko says:

    Hey, thanks a lot for commit 1716600 and fixing the UTC bug!

  44. Swards says:

    Hi – I’m having some trouble using acts_as_audited with authlogic. I’m trying to audit the user model and this is causing some issues.

    Acts_as_audited wants to access current_user when it creates an Audit, but calling the current_user method from the Application Controller will trigger the Audit creation in the first place (like when the user logs in). Because the current_user method is private, it does not add user information to the audit entry. I tried moving the current_user and current_user_session to protected, and this caused a ’stack level too deep’ error – the infinite loop as I described above.

    I can see that this may just not be meant to be, but wanted to check to see if there is a way to get these two to work well together.


  45. Swards says:

    I little more about Acts_as_audited and Authlogic together.

    Authlogic modifies the User more frequently than I understood. It updates the User object regularly – the last_request_at column updates every few seconds – depending on user requests.

    It’s the callback that comes after this update that triggers Acts_as_audited to log the update. I am also trying to resolve this from the Acts_as_audited side.

    Any help is appreciated.

  46. David says:

    Thank you!!!

    I’ve given up on Rails several times, because a simple blog example does not cut it for getting an application up fast, and I’ve always hated the tons of code that other generators produce for such a common piece of functionality. Something like this should really be built into rails; few applications use no authentication, and what happened to "opinionated software" when it comes to this? I like to start with a robust user/account model, and work inward from there, instead of designing it as an afterthought. This lets me not only prototype a full much more quickly, but is robust enough to be the final product too. Thanks to you, I may stick with Rails this time instead of going back to the horrors of php. :)

  47. Brett Kelly says:


    So, I’m a complete Rails newbie (coming from a CakePHP background, so I’m pretty familiar with most of what Rails does, at least conceptually). I’ve followed the tutorial exactly, as far as I can tell, and I’m getting this error when I visiit http://localhost:3000/user_sessions/new :

    NoMethodError (undefined method `acts_as_authentic_config’ for #<Class:0×249f064>):

    Obviously, I’m doing something wrong – if it’s glaringly obviously to anyone what that "thing" might be, I’d love to know :)


  48. evefon wu says:

    Awesome gem. Thank you! You’ve saved me a lot of time and introduced me to cool code and cool ideas.

  49. Cotter says:

    Does anyone have this working with Rails 2.3RC1? I keep getting "uninitialized constant ApplicationController." I tried the fork at http://github.com/misfo/authlogic/commits/master which mentions at least one 2.3 fix but still no joy. Any help anyone could give would be appreciated as I’d really like to use this in my application.

  50. Gustavo says:

    Cotter, I’m having the same issue. Of course, if you rollback to 2.2.0 it starts working again.