#82
Dec 02, 2007

HTTP Basic Authentication

Rails 2.0 offers an extremely easy way to do HTTP basic authentication. See how in this episode.
Download (11.6 MB, 4:23)
alternative download for iPod & Apple TV (6.6 MB, 4:23)

Resources

# products_controller.rb
before_filter :authenticate

protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "foo" && password == "bar"
  end
end

RSS Feed for Episode Comments 70 comments

1. August Lilleaas Dec 03, 2007 at 03:43

Oh, hey, that's neat. Was just googling for this. Should make REST-authentication super easy, and then using the usernames and passwords in the database to authenticate.

<pre>
authenticate_or_request_with_httpt_basic do |username, password|
  User.authenticate(username, password)
end
</pre>

Wohoo!


2. nelson jr Dec 03, 2007 at 14:22

Hi. Sorry my stupid question, but how can I do logout using http_basic? :-)

Bye


3. Ryan Bates Dec 03, 2007 at 20:48

@August, right! Since the authentication is handled in a block there's a lot of flexibility. Moving it to the user model (if you have one) is a good idea.

@nelson, that's a good question. The authentication is kept in the browser (client side), so there's really no way to log out the user on the server side AFAIK. The user will have to close the browser to end the session. I think there are hacks around this issue, but I haven't looked into them.


4. Joel Leibow Dec 03, 2007 at 22:57

I have a really stupid question. What is that Growl type notification that pops up whenever you are executing keyboard shortcuts in Textmate? That could be handy for me if I could figure out what it is and how to get it.


5. August Lilleaas Dec 03, 2007 at 23:24

@Joel: Yeah, that was a stupid question =P It's listed on the "about" page, and is called KeyCastr.

@nelson: As Ryan says, http based authentication doesn't support logout. But as we're rails developers, we should be used to using systems that's opinionated and that makes choices for us - which is exactly what http does. This kind of authentication is rarely used to authenticate users through browsers, but it's ideal for authenticating in API's and so on, as most API reading systems supports the HTTP standards.


6. nelson jr Dec 04, 2007 at 10:13

@August, @Ryan: then using Model inside the 'authenticate_or_request_with_http_basic' as used on the example, I have support to logout? The authenticate don't will stay registered on client-side?

(srry my english guys)

[]s :)


7. August Lilleaas Dec 05, 2007 at 02:17

@nelson jr: As opposed to the "normal" way of authenticating, where you set session[:user] to something (which is what e.g. the restful_authentication does), this particular method authenticates you if the stuff inside the block returns true. So, doing this would authenticate you:

authenticate_or_request_with_http_basic { true }

This is what a User.authenticate action could look like:

def self.authenticate(username, password)
  user = self.find_by_username(username)
  user && user.valid_password?(password)
end

This method returns true if a user was found and the password was valid. Otherwise, it returns false (if the password wasn't valid) or nil (if no user was found with the specified username).


8. Scott Barr Dec 05, 2007 at 05:07

@August Lilleaas

You are absolutely right. To elaborate a bit more for nelson jr, with HTTP Basic Authentication and REST you won't need to use a server-side session at all. The server authenticates you and services your request. You then cease to exist to the server, as you are not actually "logged in".

This makes running a service/site across a cluster or servers simple because your session state (logged in, not logged in etc) isn't of any concern. A subsequent request could go to any server in a cluster and it wouldn't be a problem because you provide your authentication details again.


9. Ryan Dec 08, 2007 at 20:12

I would imagine you could still create a session for the user, right?

Also, how would this work for HTTP Digest Authentication? Could you do this with OpenID instead of a Username/Password combination?


10. Patrick Dec 09, 2007 at 12:55

Hello,

I just want to say "thank you". I'm new to rails and I like it. Your screencasts are great. I don't understand each of them fully, but from day to day I understand more.

Bye,
 Patrick


11. Ryan Bates Dec 11, 2007 at 10:34

@Ryan, I don't see what benefit storing it in a session would give because the browser will usually store the login credentials on its own. If you store it in a session it will be in two different places which could get messy.

As for HTTP Digest Authentication, I don't think Rails 2.0 offers an easy way to do this. But I haven't looked into it.

Also, I don't see any way to incorporate OpenID authentication into this.


12. Joe Dec 12, 2007 at 08:47

I'm currently using restful_authentication. So, in the move to Rails 2.0, should I stick with that and "enhance" it with this? Based on August's comments, that is what is implied. Where might the code August posted be put? Sorry, my newby-ness is apparent.


13. Chris Dec 21, 2007 at 06:38

Do you know if its possible to use http to request information from the user other than login credentials?


14. Win Dec 25, 2007 at 19:30

Keep up the great work guys! As I continue my education with rails (and ruby) into the 2.0 transition, your railscasts are a breath of fresh air in the often dark tunnel I call rails newbieness of which I suffer greatly.


15. rolando Jan 02, 2008 at 22:55

@ryan
How would one do the call to such an authenticated controller from activeresource. How does one pass the request authentification at the reqest time. does that go into the model or is that a step done during the find?

I mean like so:
*model*
class Event < ActiveResource::Base
   self.site ="http://localhost:3000/"
end

*irb*
s=Event.find 989


16. Coop Jan 20, 2008 at 03:40

I haven't seen it asked yet and I've done some google-ing and haven't come up with a result either...

I want a authenticated? / logged_in? method. Because in my views I want the edit | delete links visible for the authenticated user but obviously not the general public...

Does anyone have any ideas? Thanks in advance.


17. Joshua White Feb 10, 2008 at 15:43

I set up the auth model you described and it worked great. I switched my site to using it in development no problem. Then I went live, which is mongrel w/apache cgi. I can't seem to get the username and password through to rails. Has anyone found a good way to do this. I've gone through a lot of tutorials and guessing with no luck.


18. Oskar Lissheim-Boethius Mar 11, 2008 at 16:05

http_basic only works when running through curl with http://user@pass:localhost:3000/etc, not when running in Safari or Camino--I never get a window to enter the credentials, it just passes through, and then obviously creates the dreaded "nil" error when the @user can't be authenticated and found.


19. Eilert Islaksen Mar 30, 2008 at 15:32

@Coop, no idea how to but I'm wondering the same thing.


20. Coop Apr 05, 2008 at 18:24

@Eilert Islaksen, I don't think that it's possible otherwise someone would have said something...

@Oskar Lissheim-Boethius, I use Safari and always get the HTTP box to input my details


21. Benjamin Quorning Apr 11, 2008 at 01:17

@Coop, Eilert Islaksen: I too was wondering how to combine authenticate_or_request_with_http_basic with the show/hide edit/delete links explained in Railscast 20.

The way I achieved this was to set an is_authenticated instance variable:

# products_controller.rb
def authenticate
  @is_authenticated = authenticate_or_request_with_http_basic do |username, password|
    username == "foo" && password == "bar"
  end
end

Then you can show/hide in the view by:

# index.haml
- if @is_authenticated
  = link_to …

You could add a helper method:

# application.rb
helper_method :admin?
def admin?
  @is_authenticated
end

and go:

# index.haml
- if admin?
  = link_to …


22. Joshua Jul 16, 2008 at 01:08

If you're having troubles with getting HTTP Basic Authentication working with Apache fcgi try adding this to your htaccess file.

RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]


23. ruby developer Jul 20, 2008 at 07:14

Очень простой и понятный пример. Спасибо!


24. Jasper Aug 12, 2008 at 06:18

@nelson et al.

A way (hack) to logout of HTTP-Basic-auth is to let the user follow a link to a special 'logout' resource which will always return "401 Unauthorized", after which the browser will reset the user's credentials and therefore stop sending them as such.


25. Pete Aug 14, 2008 at 21:34

@Joshua - Just what I needed, thanks!


26. Martin Sep 09, 2008 at 14:44

In finding out how to password the exception_logger interface, I came across this neat stuff:

http://errtheblog.com/posts/67-evil-twin-plugin

Here's my code:

http://gist.github.com/9771

and that's that.

Hope it helps someone.


27. Benjamin Quorning Sep 26, 2008 at 23:02

@QQ

Yeah, sorry, my code example didn’t work. I ended up using the session object to get it working: http://pastie.org/280240


28. Anthony Ettinger Sep 28, 2008 at 13:06

How would I add this to my demo and test environments?

I want basic authentication based on environemt


29. Christian Dec 17, 2008 at 07:20

Great screencast, really great!!! The comments also are very useful.
Thanks guys.


30. ujjwal kumar Jan 06, 2009 at 10:48

when I use this method on localhost, everything works fine.. but, when I host it online, the application root directory is in domain.com/local ..

in this, the authentication window comes, but it doesn't authenticate me actually.. I type the login, password, still, the window appears again and again, and if I cancel, I get:

HTTP Basic: Access denied.

The rewrite rule pointed out by Joshua even didn't work!


31. ujjwal kumar Jan 07, 2009 at 00:15

I tried a lot to write a Rewrite rule, but it didn't turn out for me.. probably the hosting provider has disabled fast cgi scripts..

Instead, I installed this plugin which has even got login/logout features.. :)

http://ariejan.net/2007/08/24/super-simple-authentication-plugin-and-generator/


32. Reuben S Jan 16, 2009 at 14:14

Thanks again for this great work.
It appears the link to the http_authentication.rb source shown above is no longer valid since the code moved to github.
I assume you might want something like: http://github.com/rails/rails/tree/v2.0.0/actionpack/lib/action_controller/http_authentication.rb


33. David Michael Jan 22, 2009 at 10:06

There are a couple of comments here asking about digest encoding of username:password so I just wanted to say that the Rails HTTP authentication library also handles a form of digest encoding - though i am not sure if it conforms to HTTP spec.

To use it, encode 'username:password' in Base64 and put it in the 'authorization' header of the request (which is where basic auth is anyway)

In curl, the line looks like this:
http://gist.github.com/50638

This is really really handy for JavaScript (and iPhone) apps accessing a resource server - especially if you do not have an SSL connection setup and do not want to send login info over the internets in the clear.


34. Division Durch Null May 19, 2009 at 07:44

It's a pitty that this function do not protect the public-folder. Do you know a possibility, sans .htaccess?


35. Joe Sep 19, 2009 at 23:18

Nice Tut! I think I may use this concept for my site. (currently implementing a new RoR tutorial system).

Had some random not working at some point with it, but I just changed the username and password and for some strange reason that fixed it.

Thanks Again,

Joe


36. Byron Oct 14, 2009 at 17:31

Hola a todos estoy iniciando con el mundo ruby on rails y necesito hacer una aplicacion web con autentificacion y con base de datos prostgres alguien me podria guiar por favor es urgente gracias mi correo cyber_daemon_one@hotmail.com


37. AYANAMI-Ueto Aya & Tamaki Nami Club Nov 11, 2009 at 05:20

this is cool, this is what we want dude......

I have received several similar emails like this one.


38. Puneet Pandey Jan 06, 2010 at 11:59

Hi,

I am trying to run a curl url from my terminal and I am getting permission denied error.

curl -H "Accept: application/xml" http://localhost:3000/readings?current_user=1

I tried this as well:

curl -H "Accept: application/xml" http://localhost:3000/readings?user_id=1

in my readings controller I have before_filter method set.

Kindly suggest me how would I fix that.

Thanks
Puneet


39. Nick Jan 22, 2010 at 08:19

Hello Ryan, first time posting - big fan...

This is killing me! I think the answer to this will help solve a lot of your commenters woes.

Im trying to do a remote authentication via json from within a JS based accelerator iphone app seen here http://pastie.org/789924 but i keep coming up with the famous ActionController::InvalidAuthenticityToken. I've been searching all night and I find myself more confused than when I started. How does one go about construct this JSON call in order to circumvent the protect_from_forgery method!

Thanks in advance and keep doing the awesome job youre doin...


40. sas Feb 01, 2010 at 02:43

Many thanks, have very much helped


41. cynthia Feb 01, 2010 at 04:28

Mark McGwire made his first public appearance in St. Louis to a crowd roaring approval.

Former Met (unfortunately) Jose Offerman punched an umpire in a winter league game in the Dominican Republic.

Nationals' GM Mike Rizzo is starting to leave his mark on the Washington roster.


42. Po Feb 28, 2010 at 12:58

NICE AUTHENTICATION HACKING PROGRAM


43. rita Mar 10, 2010 at 06:34

I just want to say "thank you". I'm new to rails and I like it. Your screencasts are great. I don't understand each of them fully, but from day to day I understand more.


44. vita Mar 10, 2010 at 23:37

this is cool, this is what we want dude......

I have received several similar emails like this one.
Report as Spam


45. Language learning software Mar 15, 2010 at 23:37

Totally,German totally based on standard software design of computer and network equipment, installation simple maintenance and update really thoroughly. No hardware terminals,Italian hardware card, hardware, without any special control network wiring.http://www.rosettastonelanguage.biz/


46. svet Apr 01, 2010 at 22:27

Great screencast, really great!!! The comments also are very useful.
Thanks guys.


47. oleg Apr 01, 2010 at 22:28

otherwise someone would have said something...

@Oskar Lissheim-Boethius, I use Safari and always get the HTTP box to input my details


48. darw Apr 01, 2010 at 22:29

when I use this method on localhost, everything works fine.. but, when I host it online, the application root directory is in domain.com/local


49. vasd Apr 01, 2010 at 22:30

Thanks again for this great work.
It appears the link to the http_authentication.rb source shown above is no longer valid since the code moved to github.


50. nona Apr 01, 2010 at 22:31

this is cool, this is what we want dude......

I have received several similar emails like this one.


51. jewelry wholesale Apr 09, 2010 at 01:08

thanks,that's good,I like.


52. hemant Soni Apr 27, 2010 at 01:40

on logout call this in java script function
document.execCommand("ClearAuthenticationCache");

to clear the cache of the browser


53. steel Apr 30, 2010 at 18:19

been looking for this life forever but didnt cant up with the keywords for search.

Cheers


54. Joe Breman May 08, 2010 at 02:33

Thanks for article. The interesting information


55. Touch Screen LCD Monitor May 26, 2010 at 00:31

good post.


56. China fashion jewelry Jun 02, 2010 at 00:02

That's is useful. Thanks for your efforts!


57. fashion costume jewelry Jun 02, 2010 at 00:03

nice code. I will try.


58. fashion jewelry Jun 02, 2010 at 00:04

Ok. This is unbeleveable excellent!


59. Joe Jun 05, 2010 at 11:32

I can't get this to work, it always gives 401 unauthorized and never asks for a username/password. If I use curl and give it a username and password though it works, can anybody help me out?

Thanks


60. Buy Christian Louboutin Jun 07, 2010 at 20:43

Really trustworthy blog. Please keep updating with great posts like this one. I have booked marked your site and am about to email it to a few friends of mine that I know would enjoy reading..


61. продвижение сайтов Jun 09, 2010 at 00:30

Thank you,I think it's very useful.
займите первые места поисковых систем и ваш бизнес будет процветать


62. Cheap Vibram Five Fingers Jun 11, 2010 at 01:32

I am the first time on this site and am really enthusiastic about and so many good articles. I think it’s just very good.
Always yours


63. fitness Jun 15, 2010 at 18:53

thanks a lot for this, Let's keep healthy from now on.


64. ghd flat iron Jun 15, 2010 at 18:55

that's great to see this,you can design your hairstyle by yourself.


65. eartha Jun 25, 2010 at 01:30

http://www.newmbtshoe.com


66. eastnike Jun 29, 2010 at 20:14

http://www.east-nike.com/


67. shell Jul 09, 2010 at 00:16

thanks for it.
<a href="http://www.airmaxgoshopping.com/nike-free-run-c-44.html"><strong>Nike Free Run+Running</strong></a>
<a href="http://www.airmaxgoshopping.com/"><strong>Nike Lunar Glide</strong></a><p>


68. vibram five fingers Aug 01, 2010 at 23:42

I recently came across your blog and have been reading along.
I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading.Nice blog,I will keep visiting this blog very often.


69. timberlandbootsuk Aug 02, 2010 at 02:08

we provide our buyers with an efficient and manageable procurement process covering every phase of the international supply chain and

streamlining trade channels. Also welcome wholesaling, feedback now!


72. VibramFiveFingers Aug 05, 2010 at 00:06

I am the first time on this site and am really enthusiastic about and so many good articles. I think it’s just very good.
Always yours


73. jordansneaker Aug 10, 2010 at 18:12

A blind man who leans against a wall imagines that it's the boundary of the world.


74. jordan retro shoes Aug 10, 2010 at 23:47

<a href=http://www.kicksbar.com>jordan retro shoes</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. i love
<a href=http://www.kicksbar.com>jordan retro shoes</a> very much. Duis te feugifacilisi. Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.


75. free directory list Aug 11, 2010 at 22:23

Thanks for very good information.


76. baby furniture Aug 13, 2010 at 05:40

This post contains very important information as well as knowledge. Keep us updating and thanks for sharing it with me.


77. emrah eren Aug 13, 2010 at 16:13

hello thank you good information


78. vibram five fingers Aug 16, 2010 at 10:27

Hey, I read a lot of blogs on a daily basis and for the most part
people lack substance but
I just wanted to make a quick comment to say GREAT blog!…..
I’ll be checking in on a regularly now….
Keep up the good work!


79. Vertu Ascent Aug 18, 2010 at 23:37

Nice blog, looking good. :)


80. jordan retro shoes Aug 19, 2010 at 00:18

Thanks for very good information. Excellent article that will provide the incentive and basis for my works.I wonder if I can mention the article as a bibliographic reference in my work. Thanks!


81. Air Rift Aug 19, 2010 at 02:04

Thanks for posting! I really enjoyed the report. I’ve already bookmark this article.


82. Nike Slippers Aug 19, 2010 at 02:46

I was reading something else about this on another blog. Interesting. Your position on it is diametrically contradicted to what I read earlier. I am still contemplating over the opposite points of view, but I’m tipped heavily toward yours. And no matter, that’s what is so great about modernized democracy and the marketplace of thoughts on-line.


83. medyum Aug 20, 2010 at 09:40

nice share.thank you


84. medyum Aug 20, 2010 at 09:42

Very nice sharing.thanks


85. Chaussures Nike Aug 23, 2010 at 21:31

Nice blog. The content of your blog is exactly wonderful, and your blog template is Simple generous. So good


86. louis vuitton shoes Aug 26, 2010 at 21:03

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


87. snow boots Aug 31, 2010 at 00:44

What is that Growl type notification that pops up whenever you are executing keyboard shortcuts in Textmate?


88. louis vuitton sunglasses Sep 01, 2010 at 21:42

Good post, I can’t say that I agree with everything that was said, but very good information overall:)

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source