C# 4 ASP.net *NON MVC* Custom Authentication - c#

I know this question as been asked countless times, but believe me I've searched Google for hours and got nothing. Whatever is out there, it's for MVC, which I'm not using.
My requirement is simple. I do not want to use the default authentication provided in asp.net. I would store the username/password/role in my custom SQL Server table. I'll provide 2 inputs for username/password and a button to validate. On validation, he is allowed access to the admin areas. This will only be used by admin guys at my subdomain "admin.*.com". They will use this page to add content to the website on daily basis.
How do I implement it. A tutorial link would suffice.
Is it safe for Production? I don't want some newbie hacker getting in to my site and mess it up. If not safe, what else option do I have.
Thanks,
Dev

As per our comments, given your reluctance to implement an ASP.Net Membership provider (and it is worth the time to investigate - you may not feel that it is right now, but it can be handy. I felt the same way at first, but the cost of maintaining your own code and infrastructure soon proves to be false economy) you have at least two other choices:
1) Straightforward Forms Authentication
Put all of your admin pages under a single folder, for example, /Admin, then use Forms Authentication to protect access to this folder. Only users defined in the database or Web.Config will have access to these pages. This is less flexible than ASP.Net membership, but may give you most of what you want. In terms of security, this will be as secure as your website is, is well tested, and is well documented.
2) Use Facebook OAuth
You mentioned that your use has access to Facebook. You could use Facebook to do the authentication for you. Although you wont be able to grab the username and password, you can get a token back, that you can then validate against a known permission set. This is a lot more work than 1) though and will tie you to potential future changes in the Facebook API. However, it also benefits from being well tested, and secure, but you have little to no control over the actual user information.
As an aside, please also consider being nicer to Google!

You can create your own custom membership provider which has the features you are looking for.asp.net membership provider
Its best to use the tried and tested method for security purposes. Remember you can customise any providers including role providers or even create your own unique providers.

Here is an example how to LDAP authentication using ASP.NET 1.1. The logic may still be applicable or can be adapted to later versions of ASP.NET, although I have not tested it.
Using the built-in membership providers, or implementing your own, is no guarantee that a hacker can't get access to your system. Things you'll have to consider:
encrypting data between client and server
don't store passwords in the database, not even encrypted. Hash each password its own salt, if you can.
enforce strong password entropy.
make sure session and authorization cookies are marked HttpOnly and Secure
for admin passwords, have a policy to change them frequently (like once a month)
provide means to notify administrators when someone signs in to their accounts
temporarily lock out ip address who exceeds number of requests per second and failed to authenticate
temporarily lock out users when they enter their password more then x (e.g. 10) number of times in an y number of minutes (e.g. 10).
These are just a handful of things to look for. You'll also have to concern yourself with session highjacking, javascript attacks and so forth.
Its not a trivial matter.

Writing a custom authentication handler is very dangerous. There are many ways to get it wrong and leave your website vulnerable to attack.
I also understand your complaint that Forms Authentication is extremely complicated. I was faced at a similar cross roads and decided to build my own authentication system called FSCAuth. It's BSD licensed. It's designed to be super simple and to allow for just about any database format you can image. All that must be done to set it up is implement a small 4 function interface into your database and populate a few configuration fields.

Related

ASP.NET Single Sign On

We have two servers that run on the same machine under the same domain.
Both written in ASP.NET and uses the Identity framework.
I need to implement Single Sign-On (and single sign out) between them.
Actual sign-in is done in AJAX (I POST the username and password, the server authenticate the user and sets the session, then sends the redirect data URL to the client).
I found overwhelming amount of information about OWIN, the Identity framework, Claims, etc.
I found tutorials explaining how to create projects using just about any modal dialog and any Wizard there is in Visual Studio, which I tried to understand but really is useless to me, as I already have authentication system up and running.
I even found some demos claiming to implement SSO in all kinds of ways, and some Stackoverflow questions that said to simply put this and that values in the web.config and you're done, which seemed strange to me and I figured out I'm missing some basic understanding of how it works.
Still, I can't understand how SSO works in ASP.NET Identity.
Can someone please explain it to me in a simple manner, or refer me to some kind of such explanation?
Again: I have two authentication systems up and running. What code and/or configuration changes I need to make to get Single Sign-On working?
First, if you want them to share authentication, they need to be working on the same user store. In other words, you should factor out the Identity initialization code (ApplicationUser, ApplicationDbContext, ApplicationUserManager, and ApplicationSignInManager) into a class library that both applications share. Trying to mantain and share two separate databases with user data is going to be an impossible and insurmountable task.
Then, you need only ensure that both applications utilize the same machine key. The auth cookie is encrypted, and since the encryption is based on the machine key, both applications need to use the same key to encrypt/decrypt that cookie.
Since you've already stated that they will both be hosted on the same domain, that's all there is to it.

FormsAuthentication.SetAuthCookie stores data in which place

In the following code where the creating user accounts(userid, password) stores in?
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
Sameway, When LogIn, how it works?..(i.e)How the values are retrieved and compared to the data we are typing in the login page(userid, password)..Please explain the process..I am having doubt whether it is storted in ASPNETDB.MDF - > aspnet_Membership..If the values are stored here, then how application works when retrieving values from here to compare the data we typed in the form..Here the application I mean is Sample Application present in .NET4.0(Visual Studio 2010)..Pls help..
UPDATE: 24/12/2012
Below answer is out of date. The venerable FormsAuthentication.Authenticate is now marked as obsolete in ASP.NET 4 MVC 4.
MVC 4 ships with the new brand spanking WebSecurity authentication system which solves a lot of problems of the old system. Please look in to it unless your project is still using MVC 3 or below.
Short Answer is "It works very carefully."
Long answer...
User account details are (by default) stored in a SQL CE database (which is in the ASPNETDB.MDF file)
ASP.NET has a built-in Membership and Role Provider system to assist with authentication. This is an abstraction that ASP.NET uses to enable built-in support for accounts. By default, when you create an application, your web.config file is configured so your application uses a built-in implementation of this Membership Provider to allow your application to do the magic of reading and writing to the database, hashing or encrypting passwords, validating users .etc.
The code sample you got, is a part of Forms Authentication
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
It is the component that manages Authentication by default. When you perform the above call, ASP.NET Forms authentication system encrypts the username and a session data and stores it in a cookie on your user's browser. (This cookie is removed when you call FormsAutentication.SignOut() )
This cookie is transmitted to your server for every request. So, for each request, FormsAuthentication checks and validates this (decrypts it, check who the user is, validates the session is not expired, and set some properties in the application so your code can know which use is making the request).
If the /* createPersistentCookie */ parameter is set, the cookie is set as persistent, which means the cookie doesn't get deleted when you close and re-open the browser while logged in. This is same as you logging into, say Facebook, and tick the 'Remember Me' check box, and the default implementation of the project created by Visual Studio does exactly this on your log in page.
Hopefully now you have a better understanding about what's happening in the login process. Because of the way these are implemented in ASP.NET, you can easily configure, extend or replace the functionality with your own implementation if you like.
To better understand how things work, follow this article on how to implement a custom Membership Provider http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
I should tell you that if you're new to ASP.NET, reading on how Membership and Authentication works may be overwhelming. (I personally spent the last couple of days trying to understand and write a custom Membership provider to match my requirements. It was a bit frustrating so I took a break to answer you and refresh my mind with the basics.)
If you're happy with how the existing system works, just use it. It doesn't hurt to implement a custom provider to understand how it works. But the built-in system has went through a lot of testing for the last decade and proven to be working. So why not use it ? I've seen multiple custom implementations on different sites that try to replace the existing Membership system, just because they don't fully understand it. Most of these implementations end up re-writing what is already available, and falls short when it comes to extensibility and security. Just like a wise man once said "Don't fix it, if it ain't broken".

ASP.NET - authentication against multiple domains

My website can be access from many domain (a my own blog engine). So, how i can cross authentication?
I'm using: IIS7, C#, asp.net membership, form authentication.
If you are using Active Directory (assuming that is what you refer to as domains), you can simply configure multiple ActiveDirectoryMembershipProvider sections and use the asp:Login control templates, add a dropdown for the domains you want to authenticate against, and on the OnAuthenticate event of the Login control, set the selected AD membership provider.
For different providers like SQL Server membership provider, I'm not sure I understand what the issue is. Can you elaborate?
I'm going to take a guess here after having tried to read your question a couple of times again. If with 'multiple domains' you mean you have multiple websites (multiple fully qualified domain names), and you want to use the same SQL Server datastore to authenticate users against, and run the same website, the solution would be to point the appropriate DNS A record to the IP address of the original hosting server.
Any decent domain registrar should allow you to change the DNS record.
However, Forms Auth creates a cookie, and you will not be able to read the cookie from a different domain than that you are on because of obvious security issues, so in that case you're stuck.
The only possibility I can see is that you're passing some encrypted identity in a querystring, but that is very, very dodgy, as you would want to make sure there's a minimal validity time limit on it as it opens up a right can of worms (security holes). Probably not recommended.
Crikey, that's a long way of saying "No, you can't - securely."
If are talking about sub domains and not about different top level domains, then you can actually do it, see this post.

Membership Providers and HIPAA Compliance

Does anyone know if the provided SQL and Active Directory Membership Providers in ASP.NET 2.0+ are HIPAA compliant?
Clarification:
I understand that HIPAA mandates patient information be secured and that certain policies be put in place to secure access to that information. Can Microsoft's SQL and AD Membership Providers be used for handling the authentication of users accessing this information? I expect there to be some policies that need to be established like password length and complexity but is there anything inherit about the way they store information that would invalidate them for the purposes of authorization? Any gotchas or things to look out for?
It depends on what you want to do with them, but in short, yes. HIPAA is all about standards for securing your data; the standards aren't particularly harsh, so long as you have a way in place to provide for security. In that way, it's a lot like ISO 9001; so long as you define a security policy and stick with it, you're okay. The mentioned providers are effectively tools.
That said, you may need to do some additional things with your data to assure that it's only clearly accessible from your application; some level of pre-encryption would probably be appropriate. Just understand that it probably doesn't need to be HEAVY encryption; very light would do, so long as you're consistent with the application of it.
I sure hope it is;) We currently use the 2.0 Membership Provider with an ADAM LDAP at the health insurance company that I work for. HIPAA and PHI are the name of the game here and this set up went through our legal department.
I'd say that out of the box, it is not HIPAA compliant.
The way to find out would be to create a new Web Application, with just a default.aspx and maybe a login page. Then click the "ASP.NET Configuration" tool in the Solution Explorer toolbar to launch the configuration application (you can also do this from IIS if your site is hosted there). Set up the defaults, choosing to use the AspNetSqlProvider for all features.
This will create an ASPNETDB.MDF in your App_Data folder. Right-click it and choose "Open". This will open it in Server Explorer, where you can look at all the tables that were created.
You'll find that the password is stored hashed in the aspnet_Membership table, instead of as plain text. That's a good thing. However, the email address is also stored in the clear. If I remember my HIPAA training from four years ago, that's PII, and should at least pretend to be special. As it is, anyone with access to the database could find the email address of any member.
Edit based on update:
If you're only talking about using them for authentication and authorization, I'd say you're ok. You will need to ignore the email address.

How to allow multiple authentication methods in ASP.NET?

I'm building a new ASP.NET MVC application (in C#) and one of the requirements is to create a new database of members. For this, we'd need roles to manage the different types of members and profiles to manage the additional metadata attached to each member. So far so good, just use the standard MembershipProvider, RoleProvider and ProfileProvider provided as part of the .NET Framework.
However, the catch is that I'd like to allow different authentication methods. I'd like Accounts and Login Credentials to have a one-to-many relationship (one account can have a number of login credentials attached). A user for example, might have both an OpenID and ActiveDirectory account attached to their account.
However, after experimenting with a few ways we opted for the MembershipProvider route (explained how it was achieved as an answer below).
My question is, how have people done this before and how would people suggest I approach it? It appears to be something that is achieved on quite a number of sites, yet a search on here doesn't return anything solid to play around with.
EDIT: After looking around for a good period of hours overnight and this morning - I'm still not convincinced that butchering a single MembershipProvider would have been the easiest option. Does having multiple MembershipProviders give the same effect?
BOUNTY EDIT: With no responses, I am assuming that there is no more optimal solution that the one I posted as an answer. Is this really the case? I'm offering a bounty to try and see if anyone has any further thoughts on this and whether there are better alternatives.
BOUNTY ACCEPT EDIT: I think that WIF is the answer as accepted below, for a .NET 4 release and maybe other versions as it probably works with 3.5. Other than that, maybe a butchered MembershipProvider or adapted one may still be relevant.
In my opinion, the "real way" of doing this is to use federation with WIF (Windows Identity Foundation, formerly Geneva framework).
The idea is that you separate authentication from authorization. The authentication is performed by a so-called STS (Security Token Service) and it manages all the possible login mechanism that you want to support. When a user has been authenticated the STS issues a token containing a set of claims and the user's identity.
This token is sent to the web site (called a relying party in this lingo), and the website determines which parts of the site the user has access to based on the claims in the token. WIF supplies both membership and role providers that extract information from token.
You can read about creating a claims aware website here.
One of the pros of this approach is the separation of concerns between authentication and authorization. You do not need any complex membership and roleproviders in your website. Furthermore the STS can be reused to authenticate users to other applications you might have without them having to register more than once (effectively achieving single sign-on)
The downside is that you will have to spend some time studying these concepts and coding your STS. Mind you, it is not hard to code an STS with WIF, but it is not a 100% trivial task either.
If I have managed to tickle your interest I would recommend that you start out by reading this whitepaper.
Kind regards,
Klaus
One idea we've followed is to create a custom Membership / Role / Profile provider. We customised the login / authentication methods significantly and have an additional table of logins. This table basically just contained:
LoginID (Auto-Incremental ID, PK)
UserID (FK)
LoginSystemID (FK)
...blah blah
Within the above, the LoginSystemID was a link to a foreign lookup table which helped the system to determine which authentication service to use (e.g. Standard, AD, OpenID, FacebookConnect - etc).
The problem we ran into was that the Username field in the MembershipProvider couldn't be empty and while in our schema everyone had a UserID (it was their account name), they didn't have a Username that was unique. We had to get around this by generating a GUID and using that. This of course is hidden from the user and a DisplayName attribute from our Users table can be displayed instead.
This was all done via FormsAuthenication (the AD checks were done via LDAP checks). However, an additional layer (a webform) was added with appropriate settings within IIS that provided a means for automatic WindowsAuthentication - we redirect to there in the instance that we feel the user is likely to be internal (based on IP address).
Use standard framework stuff. See http://blogs.teamb.com/craigstuntz/2009/09/09/38390/
You can have an unlimited number of authentication methods attached to one account, the magic is in the FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); statement

Categories