Click here to Skip to main content
15,885,216 members
Articles / Web Development / ASP.NET

Basic authentication in ASP.NET against custom datasource

Rate me:
Please Sign up or sign in to vote.
4.52/5 (12 votes)
5 Jun 20063 min read 97.9K   1.9K   38  
An alternate to basic authentication using IIS
using System;
using System.Data;
using System.Data.SqlClient;
using System.Security.Principal;

namespace santosh.web
{
	/// <summary>
	/// Summary description for SQLAuthentication.
	/// </summary>
	public class SQLAuthentication : security.BaseAuthenticationModule
	{
		private SqlConnection conn;
		/// <summary>
		/// Initializes a new instance of the <see cref="SQLAuthentication"/> class.
		/// </summary>
		public SQLAuthentication()
		{
			REALM = "Test Realm v2";
			conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnStr"]);			
		}
		/// <summary>
		/// Authenticates the specified credentials.
		/// </summary>
		/// <param name="Credentials">The credentials (Username and Password).</param>
		/// <param name="Roles">The string array containing roles.</param>
		/// <returns></returns>
		/// 
		
		protected override GenericPrincipal Authenticate(string[] Credentials)
		{
			// Please override with your own logic of authentication

			GenericPrincipal UserPrincipal = null;
			string SQL = string.Format("SELECT [Roles] FROM [Employees] WHERE [username] = '{0}' AND [password]= '{1}'", Credentials);
			SqlCommand cmd = new SqlCommand(SQL, conn);
			conn.Open();
			object oRoles = cmd.ExecuteScalar();
			conn.Close();
			if(oRoles == null || oRoles == DBNull.Value)
			{
				return UserPrincipal;
			}
			else
			{
				string[] Roles = oRoles.ToString().Split(';');

				UserPrincipal = new GenericPrincipal(new GenericIdentity(Credentials[0]), Roles);
				return UserPrincipal;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
[MCSD, MCDBA]
I have been with IT since past 6+ years, working as software engineer for IBM Kolkata. .NET is the platform of my choice and coding with C# since its evolution. Please join .NETIndia http://groups.yahoo.com/group/dotnetindia group for more articles & .NET discussions.

Comments and Discussions