Wednesday, July 11, 2007

HTTP Server - Password protection

Earlier we introduced an open source embedded HTTP server. The framework comes with some very simple sample code to run it. This post will show how to extend the server to add suppport for password protection.

Say we want to specifically protect the "private" directory. We simply subclass the HTTPConnection class, and replace the "isPasswordProtected" and "passwordForUser" methods as follows:



@implementation MyHTTPConnection

- (BOOL)isPasswordProtected:(NSString *)path
{
if([path hasPrefix:@"/private"])
return YES;
else
return NO;
}

- (NSString *)passwordForUser:(NSString *)username
{
return @"password";
}

@end



Then we simply instruct the HTTPServer to use our subclassed connection class:

[httpServer setConnectionClass:[MyHTTPConnection class]];

And that's all there is to it. Now you can browse your Sites directory as normal, except your ~/Sites/private directory will be password protected.

Download it here.

There's a lot more that can be done with the server, such as serving up custom dynamic content, TLS encryption, etc.

4 comments:

Aqua Connect said...

Thanks for the info. We have been looking for a good passworded HTTP Server via cocoa. This project looks interesting we'll keep an eye on it. We are looking into using this for our up coming Enterprise Edition's console project.

-- Aqua Connect Dev Team

Robbie Hanson said...

I've heard about your great product. Let me know if you have any questions.

Casao said...

This is pretty much exactly what I was looking for.

For reference, I'm working on a plugin for Adium that'll allow it to serve up content (buddy lists, logs and messages) over the net and allow you to hold conversations in a browser while still having all messages logged in Adium (similar to the IM Everywhere plugin for Trillian on Windows)

I'm especially interested in the dynamic content you mentioned - is there any way you could elaborate on exactly what you meant? I'd really appreciate it.

Either way, thanks for making this awesome code and for putting it out there for others to use. Saved me a lot of time and effort reinventing the wheel.

Robbie Hanson said...

Hi casao,
For the latest code check out the google code page.

You can return dynamic content by simply overriding the dataForURI method, and return whatever you want.