Simple Username / Password Authentication WITHOUT Membership Providers

by ashic 19. June 2009 00:44

The Membership provider in asp.net is great. As is the Roles support. You can do some very nifty things with it with a considerable amount of ease. You can get hashed or encrypted passwords and a whole host of features that’s pretty much enterprise grade. And you get it for free. Well, not free, but it is pretty easy to set up.

But what if your website only needed two or three user accounts? What if you didn’t need all that fancy stuff. You just want to use a login system that’ll just block off an admin area or something and you want to do it quick and dirty. Maybe it’s a prototype. Maybe it’s your own little site where you just want simplicity for authentication. I’ve actually went through all the aspnet_regsql.exe trouble for a very simple site that would have just one user. Sounds like overkill? It is.

The login controls provided in asp.net 2.0 are quite handy, but they mostly work with a membership provider. The <asp:Login> control is specially helpful for creating a login screen in no time. But it too works with a Membership provider.

So how can we quickly setup a login system without using a Membership provider? And how can we use the <asp:Login> control to set up the login screen when using such a system? Read on…

Forms authentication actually allows you to store usernames and passwords in the web.config file. A typical web.config file doing this is shown here:

 

login-1

I’ve highlighted the important parts. The authentication mode needs to be Forms. The PasswordFormat is left as “Cleared” here. It can also be hashed or encrypted. I’ll make a post in the future about hashed and encrypted passwords. I’ve added a single <user> to the credentials node. You could easily add more. In the <authorization> node, I’ve allowed all users. In the <location> node for the “admin” folder, I’ve set it to deny all unauthenticated users. So, if a user is logged in, they can access the admin folder. If not, they’re asked to login.

Now, with this in place, if you were to put an <asp:Login> control on a page and expect it to work just like when using a Membership provider, then you’re in for a nasty surprise. Even if you enter the correct username and password, it’ll tell you the login has failed. Why? The reason is pretty simple. We’ve not mentioned a Membership provider to use, so asp.net defaults to the Membership provider in the machine.config, which usually is an asp.net sql membership provider drawing info from a database in App_Data. That database has no info about our user named admin with the password “pa$$w0rd!”. So, logging in fails. How do we overcome this? Simple. Just add a handler for the OnLoogingIn (NOT OnLoggedIn) event of the <asp:Login> control and in that handler, do this:

login-2

[If you don’t want the authentication cookie to persist between requests, set the second parameter of RedirectFromLoginPage to false.]

 

That’s all there is to it.

Now, that was very simple, but the question that pops up is is it secure?

Well, the answer is both a yes and a no. It’s yes in the sense that IIS will never serve anything with a .config extension from an outside request. So, users on your site will never be able to download the web.config and look at the username and passwords. The “no” part of the answer comes from the fact that if someone can look inside the web.config file, they’d be able to see the usernames and passwords. If you run your own server or have a hosted account that only you access, this is not that big a problem. [I add the latter coz no hosting company is ever going to go through the risk of looking inside of clients’ files for passwords.] For extra security though, you can use hashed or encrypted passwords in this system too, which I’ll cover in a future post.

A drawback to this is that the web.config file can get very big for a lot of users. But then again, this isn’t meant to be used for a lot of users. This is meant for very simple sites woth very few users. There are sites out there that are like this and don’t need all the Membership gloss. If your site’s like that, you can easily use this method.

 

Hope that helps.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: ASP.NET | ASP.NET

Display Modes of Validator Controls

by ashic 15. June 2009 23:04

By default, asp.net validators are positioned right next to the control they validate. You can move them in the markup, but wherever you put them, they occupy an area equal to the area required to display the Text property (or if the Text is not present, then the ErrorMessage property). We may not want that. We may want them to only occupy space when they’re displayed, or not display them at all (and showing the error message in a validation summary only). The validators have a property called display, which can be set to one of three values: Static, Dynamic and None. Setting it to Static will mean the validator will occupy space even when there’s no error. Dynamic means that it won’t occupy space when there isn’t an error, but will show up when there is. None means that the validator’s Text (or ErrorMessage) isn’t displayed at all and doesn’t occupy any space. In this case, you’ll need to use a ValidationSummary control to be able to display the ErrorMessage.

Let’s look at a bit of markup that has three required field validators having different settings for Display. To the right of each validator, I’ve added the text “dummy” to signify where the validator’s display area ends. Markup:

val-pos-1

 

Now let’s fire up the page and see what it look like in the browser:

val-pos2

Notice that since the first validator had a display of static, there’s a space equal to the space needed to display the Text of the first validator next to the first text box. The second and third validators had display set to “Static” and “None” respectively. Hence, there’s no space between the second and third textboxes and they’re respective “dummy” texts. Now, lets hit submit:

val-pos3

Notice that the Text of the first two validators are displayed next to the text boxes, but the third one’s Text is not shown at all. This is because the third validator’s display was set to none. Notice that the error message of all three validators are displayed in the validation summary.

 

Hope that helps.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: ASP.NET | Validation

A Cool Bing-like Search Box (Button on the Inside)

by ashic 15. June 2009 18:57

In the recent “web 2.0” sites, we see cool search boxes, with the search button appearing “inside” the text box. How’d they do that? Microsoft’s bing search also has this feature. A snapshot of the bing search box looks like this:

search

It’s actually quite simple to do, with a bit of css. First, let’s look at the markup:


<div class='search-box'>
    <asp:TextBox runat="server" ID='txt1'></asp:TextBox>
    <asp:Button runat="server" ID='btn1' Text='Search' />
</div>
 

And let’s now see the associated css:


<style type="text/css">
    .search-box input
    {
        border:none;
    }
    .search-box
    {
        display:inline;
        border:1px solid #000000;
    }
</style>
 

And you can see the result:

my-search

Sure…it’s not exactly the same, but you can play around with it, change the css here and there, use an ImageButton or whatever to make it look exactly like you want. The idea is basically the same.

Hope that helps.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: ASP.NET | HTML

Retrieving the Password for a User in Asp.net

by ashic 13. June 2009 19:30

If you’re using the Membership API in asp.net and need to retrieve a user’s password, you can do so by doing this:

MembershipUser user = Membership.GetUser("username");
string password = user.GetPassword();
string saferPassword = user.GetPassword("password answer");

The latter is safer as it requires you to pass in the user’s security answer as an added check. This will give you the unencrypted password [The default membership system stores hashed passwords in the database].

To support this feature, you’ll need to have password retrieval enabled in the web.config. You can do this in the <membership> node under <system.web>. It’ll look something like this:


<membership defaultProvider="myProvider">
      <providers>
        <add connectionStringName="LocalSqlServer" enablePasswordRetrieval="true"
          enablePasswordReset="true" requiresQuestionAndAnswer="true"
          applicationName="/" requiresUniqueEmail="false" passwordFormat="Encrypted"
          maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
          minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
          passwordStrengthRegularExpression="" name="myProvider"
          type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
     </providers>
</membership>

Hope that helps.

As Richard points out, hashed passwords cannot be retrieved. The hash is one way while having the password format set to encrypted enables retrieval of passwords. I’ve updated the web.config code to ensure that passwords can be retrieved.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: ASP.NET

How to Programmatically Logout / Disable a User Account

by ashic 13. June 2009 17:29

There may be the need to programmatically logout the user in an asp.net application. If you’re using Forms authentication, this is very simple to do:

FormsAuthentication.SignOut();

You may also need to block the currently logged in / specific user from the system. This may be needed to avoid th possibility of someone doing brute force attacks to get to site data (once they’re logged in). This is also quite simple:

MembershipUser user = Membership.GetUser(); //to block currently logged in user

MembershipUser user = Membership.GetUser("username"); //To block a specific user:

user.IsApproved = false;
Membership.UpdateUser(user);

To unblock the user, all you’d need to do is:

MembershipUser user = Membership.GetUser("username");
user.IsApproved = true;
Membership.UpdateUser(user); 

Hope that helps.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: ASP.NET

Speaking at Microsoft Day @ Dhaka- June 20, 2009

by ashic 12. June 2009 09:04

It’s finally happening…we’re having an MS dev (and IT) event here in Dhaka, Bangladesh. This is the first one ever and marks a significant landmark for the software industry here. It’s going to be held on June 20, at IDB Bhaban Auditorium. You can find details and register (mandatory) for the event here:

http://msdnbangladesh.net/content/msday.aspx

Seats are limited…only 200 in total. It’s open for devs, IT pros and students.

I’ll be doing a half hour session on Windows Azure, from 2:45pm to 3:15pm. It’s the first time I’m doing something like this, and I hope it goes well.

If you’re a dev / IT pro / student enthusiastic about MS technology, then register and be there. The MVPs from Bangladesh will be there and they’ll be doing sessions covering asp.net, MVC, silverlight 3, Win 7, IE8, Office 2007, VS 2010 Team System, Windows Live, MS Project, Sharepoint, Exchange Server, SQL 2008 – just be there…ok?

[The final agenda will be put up on the site on June 15.]

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: .NET | ASP.NET | Community

Finally Set Up My Own Site: BlogEngine.Net

by ashic 9. June 2009 08:12

I’ve been looking to set up my own site for quite some time now. The things I had in mind required a great deal of development and, due to my workload with completing graduation and a few client projects, I just couldn’t find the time. In the last few weeks, I’ve been looking at alternatives to doing the whole thing on my own. I looked at a few offerings:

1. Graffiti

2. Umbraco

3. Dnn

4. AxCMS

5. BlogEngine.Net

 

The things I was gunning for:

1. Easy to set up

2. Easy to administer

3. Easy to extend

4. Easy to change the look

5. Must support adding my own pages / running my own code on a few pages

6. Something I can work on in my free time – not something one shot (as in you upload and it’s fixed, unless you spend hours developing)

7. Not cause me any headaches

8. Cost

 

1. Graffiti

Well…I looked here and there and I found a cool post by Joe Stagner (http://misfitgeek.com/blog/community/my-move-to-graffiti/ ) and I thought it was the right place to begin. I downloaded the express edition. I installed it and my initial reaction was “hmmm…let’s see if it gets better”. Playing around, it seems a very good package that does what it’s touted to do – it publishes content. Now, I wanted to be able to create a gallery like page that I may need for tutorials. I wanted something that would allow me to code Asp.net and not just html. Wasn’t exactly the easiest thing to do. I spent a couple of hours wanting to find out how to do it. Couldn’t. It seems everything is a blog post –and if you’re ok with that, Graffiti is awesome. I’m looking for some extensibility – without getting into the labyrinths of the API. For this, I can’t support Graffiti. Very reluctantly, I moved on. Sorry Telligent. Sorry Joe.

2. Umbraco

I’ve been looking to give umbraco a run for quite some time. I nearly used it way back in ‘04 when my boss wanted me to look at a few CMSes. At that time, the priorities changed and the CMS stuff was left in the dust. Umbraco was a nightmare to install back then – that didn’t help its cause.

So I download umbraco, installation is a breeze. Although, on my dev Win7 machine, I needed to change a few settings in IIS. I remember having to use the classic pipeline and also having to have umbraco in the root. That means it didn’t work in a sub folder of Default Website, even when configured as an application. I was looking to use the CMS at the root of my site, so that wasn’t a (big) problem.

This time, my reaction was “Whoah…this is cool.” The admin tool is awesome. It worked well with SQL Server. I was happy. Then came the extensibility test. One of the things umbraco is famous for is supported developer created modules (user controls). Since I had this in the back of my head, I thought umbraco would be a sure shot winner here. Unfortunately, it was not so. Yes, umbraco is very extensible. Yes, it can be made to do anything I want. Thing is, I didn’t want to have to “make” it do anything. I didn’t want to have to learn an API just so I could run my own Asp.net code. From Joes blog post mentioned earlier: “It’s flexible, really flexible. I’m sort of in a hurry. Umbraco wants to be embraced.” Also, my blog was at http://weblogs.asp.net/ashicmahtab – that’s on Community Server. It can export BlogML. I wanted those posts on this site. I wanted feeds to be done automatically. The blog modules for umbraco seem to be left wanting in terms of features. Sorry Neils…it would have taken too much of my time to get to where I wanted to be.

3. Dnn

Disclaimer: I hate dnn. Yet I am forced to work with it from time to time. Possibly that’s a reason for my hatred. It’s freakin’ awesome and it’s a freakin’ nightmare. It’s overkill for most things. It has some really cool features, but there’s a lot of bloat. And talk about extensibility – I can do anything if I create a module for it. But creating a module for each and everything isn’t my cup of tea. It’s counter-intuitive. Still, I installed it. installed the blog module. Made a few blog posts. It was acceptable. But I wasn’t happy. It’s blogging features wasn’t exactly great, but it was the best I had till then. It may have even made it’s way to my site. Hey – there’s even a LiveWriter plugin.

4. AxCMS

This used to be a pricey product, but it’s free in toned down mode. Unfortunately, it was too toned down for my taste. Next.

5. BlogEngine.Net

I’d actually started on getting a blog ready using dnn, when –almost by accident and reasons unknown to me, I decided to install BlogEngine. Just for laughs. Hey, I want a site, not just a blog. Still, I downloaded, set the db to SQL 2005, changed the web.config. Ran the site – doesn’t look too good, but let’s see how we can change that, shall we? I looked at how I could theme it. The admin panel couldn’t do anything –it didn’t even allow me to edit the css. So, how on earth am I supposed to style this thing. And then it hit me – there’s a theme folder with folders for each theme. And in those folders, there’s a real life MasterPage and user controls for PostView and CommentView. There’s css and images and everything. I could work with the aspx code. I could plant in any user or server controls I wanted. That’s when I started giving this some serious consideration. I started looking around for how I could put my own code and pages into the system. Well, it supports user controls very easily. Just ERROR - UNABLE TO LOAD CONTROL : path type syntax is all that’s needed. That’s HUGE. It also supports adding pages from the admin panel. There’s one drawback to that approach – the url becomes something like “www.heartysoft.com/page/pageName.aspx”. Many people don’t seem to like the “page” section in the middle there. That wasn’t too big a downer for me. Next, I saw that you can derive your custom aspx page from a BlogEngine.Net type, and it’d simple carry out all the theming and Masterpage assignment. You could then code the page however way you wanted. That’s the knockout blow right there. I can code my own asp.net code and seamlessly integrate it into BlogEngine.Net. So, I put my site up. And no, I don’t like the theme I’m using. I’ll probably change it if / when I get some free time. And even if I don’t, it’s still useable. I can add sections and pages that hold my own code later on when I get the time. It supports feedburner, is completely open source, works with SQL Server without any hassles, theming is changing aspx markup – just like editing my own markup. Importing from the Community Server generated BlogML was smooth on my pc (although a little trickier for my remote server – I’ll save that for another post). All in all, I’ve got my basic  site up and running in less than half a day. And the best thing is that I can change it, add to it and work it as if it’s my own app – without knowing anything about the API. Granted, I can do some cool stuff with the API, but that should be optional. I should be able to use my own code when I want to and need to – without being forced to swallow a framework. And this is where BlogEngine.Net has excelled above and beyond the others I’ve tried.

Even after installing, I didn’t expect to be quite this happy with this thing, and yet I am. If you haven’t tried it yet, go ahead. Go to the site: http://dotnetblogengine.net/ , download it now, give it a shot. It’s awesome.

Shout it
Share or Bookmark this post…
  • Facebook
  • DotNetKicks
  • Digg
  • LinkedIn
  • Technorati
  • del.icio.us
  • Google
  • Live
  • Tumblr
  • msdn Social
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • TwitThis
Categories: .NET | ASP.NET

Powered by BlogEngine.NET 1.6.1.0
Theme by Ashic Mahtab

Need an expert?

Ashic Mahtab
ashic@live.com
(+44) 07879927393

Stats

Featured Ads

 

Donations

I maintain this site and create all content entirely in my own time just to help you guys out. If you find the stuff helpful, or cool or just like what you see, I'd appreciate you chipping in to help out with the hosting costs. It's easy to do so - just click the button below - no amount is too low :)