How to configure Custom Membership and Role Provider using ASP.NET MVC4

Originally posted on Gora LEYE:

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

  • You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.
  • You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

In tis tutorial, we are going to implement and configure a custom Membership…

Voir l'original 387 mots de plus

Multi devices ( Windows Phone, Surface, IPhone, XBOX, IPAD) behaviours Factory (VB.NET)

Mots-clés

, , , , , , , , ,

Today we have a several type of devices and the number is growing. So, we have to develop our application several times.

A way to add functionality to our applications without difficult is to use a derivation of the  Abstract Design Pattern.

In this tutorial we learn how  to add functionality to several  applications and make them  use  the same Architecture but  details vary depending on the context.

Our contexts are Windows Phone, Surface and XBOX data displaying  behaviors

We will use a Portable class Library that hold the shared functionnalities.

  • Add a new file
  • choose  Portable class Library
  • Click OK
  • Check the targeted framworks and click OK

2

  • Create a ScreenBase Class 
  • 1
  • Create a PhoneScreenService class
  • Create a TabletScreenService class
  • Create a DesktopScreenService
  • 2
  • And finaly compte Module.vb as follow :
  • 3
  • To test it create a console application and référence our Portable Class Library .
  • Press F5 to run application, so you can see that the behaviour is different between windows Phone and Surface tablet.Our sample is finish but in a real world application, we must reference our portable class library in both windows Phone client, surface client, XBOX client and sower. and  implement business logic for each client,

4

Regards

ASP.NET MVC Tracking User Activity (VB.NET)

Mots-clés

, , , , , , , ,

In this tutorial, we are going to show how to track user activity and how to log runtime errors.We can use filter attributes to mark any action method or controller. If the attribute marks a controller, the filter applies to all action methods in that controller.

Typically, we create an action or response filter by creating an attribute class that inherits from the abstract ActionFilterAttribute class.

Some built-in action filters, such as AuthorizeAttribute and HandleErrorAttribute, inherit from the FilterAttribute class.

Other action filters, such as OutputCacheAttribute, inherit from the abstract ActionFilterAttribute class, which enables the action filter to run either before or after the action method runs.

The following tutorial shows how to create a simple action filter that logs trace messages before and after an action method is called.

So Lets Create an ASP.NET MVC internet application project

  1. Add a class TraceFilterAttribute that inherit from ActionFilterAttribute
  2. Override OnActionExecuting and OnActionExecuted methods as follow

3. Finally apply  TraceFilterAttribute to your controller action on wich we want to enable trace

Run application, so you will see that each request is tracking during action and after action. And we can retrieve action name, parameters, and entire route description.

The only thing to do now is log user activity on file or database Table

4. Now Lets log runtime errors :

Our TraceFilterAttribute must implement OnException of IExceptionFilter

Each exception can now be logged.

1 2

Thank you for feedbacks

Related tutorials :

ASP.NET MVC Tracking Run Time Errors

Mots-clés

, , , , , , , ,

We can use filter attributes to mark any action method or controller. If attribute marks a controller, the filter applies to all action methods in that controller.

Typically, we create an action or response filter by creating an attribute class that inherits from the abstract ActionFilterAttribute class.

Some built-in action filters, such as AuthorizeAttribute and HandleErrorAttribute, inherit from the FilterAttribute class.

Other action filters, such as OutputCacheAttribute, inherit from the abstract ActionFilterAttribute class, which enables the action filter to run either before or after the action method runs.

The following tutorial shows how to create a simple action filter that logs run time erros on only one function  and apply scenario to entire controllers.

So Lets Create an ASP.NET MVC internet application project

  1. Add a class TraceFilterAttribute that inherit from ActionFilterAttribute
  2. Override OnActionExecuting and OnActionExecuted methods as follow

1

3. Finally apply  TraceFilterAttribute to your controller action on wich we want to enable trace

2

Run application, so you will see that each request is tracking during action and after action. And we can retrieve action name, parameters, and entire route description.

The only thing to do now is log user activity on file or database Table

4

3

4. Now Lets log runtime errors :

Our TraceFilterAttribute must implement OnException of IExceptionFilter

5

Now each exception of all controllers will be catched and logged.

Thank you for feedbacks

Related tutorials :

How to configure Custom Membership and Role Provider using ASP.NET MVC4

Mots-clés

, , , , , ,

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

  • You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.
  • You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

In tis tutorial, we are going to implement and configure a custom Membership Provider using ASP.NET MVC4

Let’s go

A.  Create a Custom MemberShip Application class Library

  1. Create a class Library Project (our sample Projet name is LogCorner.SoftwareStore.Security)
  2. Reference the assembly  System.Web.ApplicationServices (Right Click Reference è Add reference => Select Assemblies => navigate to System.Web.ApplicationServices and add it)
  3. Create a Class CustomMembershipProvider and derive it from MembershipProvider
  4. Override ValidateUser as follow

1

For now we have what we need for our application security.  To go further in the implementation of Custom Membership Provider, please see our tutorial Mastering Custum ASP.NET MemberShip Provider using ASP.NET MVC

B.  Create an ASP.NET MVC4 application Client

1.       Create an ASP.NET MVC4 application Client ( Add New projet è ASP.NET MVC4 Web Application è Select Template Internet Web Appliction and Click OK)
2.       Open Web.config file
3.       Add or Replace membership section as follow

2

4. Open HomeController and Authorize Attribute to Index ActionResult

3

5. Run the application ASP.NET MVC4 application Client,  you ll have the errors below

4

6.   do not panic, proceed as follows :

Add this in your web.config (in the appSettings section):

<add key= »enableSimpleMembership » value= »false »/>

<add key= »autoFormsAuthentication » value= »false »/>

7.   Run the application ASP.NET MVC4 application Client,  you ll have another error

5

8. To fix it Open AccountController and comment  InitializeSimpleMembership , because we using Custom Membership Provider instead of Simple Membership

9. Override Login Action of AccountController  as follow :

6

10.  Run the application ASP.NET MVC4 application Client,  you’ll have  the form authentication below

7

11. Enter user credentials and click Log In, then you will have the execution workflow below :

8

9

10

C.  Configuration of Custom Role Provider

To configure custom role provider, please proceed as follow :

  1. create a class CustomRoleProvider  that inherits from  RoleProvider
  2. Overrides GetRolesForUser method1
  3. Now open web.config file of your client asp.net web application and add a RoleManager section 2
  4. Open HomeController and change Authorization as follow : 3
  5. Now test your sample. Only users who have approved login credentials and who belong to role Administrator can view Index page 4567Thank you for reading us, our next tutorial is to configure Custom Membership Provider using ASP.NET MVC4  with external login like facebook, yahoo ,  google or other relying party accounts.

If you seek information about encoding and decoding password, please read our article ASP.NET Custom Membership Password Encoding and Decoding based on key SALT using SHA-3 algorithm

ASP.NET MVC Custom Membership Password Hashing based on SALT key using SHA-3 Algorithm

Mots-clés

, , , , , , , , , , , , ,

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

  • You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.
  • You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

This tutorial  is a continuation of our tutorial  How to configure Custom Membership and Role Provider using ASP.NET MVC4

Let’s talk about password encoding and decoding and take the opportunity to introduce the Unit Of Work Pattern used to insert and retrieve data.

There exists a sequence of hash functions SHA-0, SHA-1, SHA-2 and the most recent SHA-3.

SHA-3, is a new cryptographic hash function that has been selected by NIST in October 2012 following a public competition launched in 2007, this because the weaknesses discovered on MD-5 and SHA-1 let fear fragility SHA-2 is built on the same schéma. It has variations that can produce hashes 224, 256, 384 and 512 bits. It is built on a different principle from that of MD5, SHA-1 and SHA-2 functions.

So in our tutorial, we will use the SHA-3  512 bits,

For this, it is not intended to replace SHA-2, which is at present not been compromised by a significant attack, but to provide an alternative response to attacks against MD5 possibilities standards SHA-0 and SHA-1.

A. Unit Of Work Pattern

The purpose of this article is not an introduction to Unit Of Work Pattern but a particular use of it. So for more information Unit Of Work Pattern, please read articles that deal with this subject such as http://msdn.microsoft.com/en-us/magazine/dd882510.aspx

  • Create a class library Project and reference EntityFramwork.dll
  • Generate the model and classes from membeship database (Model.Context.tt, Model.Entities.tt and Model.mapping.tt ) . If you are newly in Entity Framwork, please read our tutorial  Introduction to entity framework Code first
  • Create IRepository interface

public interface IRepository<T> where T : class
{
/// <summary>
/// Get the total objects count.
/// </summary>
int Count { get; }

/// <summary>
/// Gets all objects from database
/// </summary>
IQueryable<T> All();

/// <summary>
/// Gets object by primary key.
/// </summary>
/// <param name= »id »> primary key </param>
/// <returns> </returns>
T GetById(object id);

/// <summary>
/// Gets objects via optional filter, sort order, and includes
/// </summary>
/// <param name= »filter »> </param>
/// <param name= »orderBy »> </param>
/// <param name= »includeProperties »> </param>
/// <returns> </returns>
IQueryable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = «  »);

/// <summary>
/// Gets objects from database by filter.
/// </summary>
/// <param name= »predicate »> Specified a filter </param>
IQueryable<T> Filter(Expression<Func<T, bool>> predicate);

/// <summary>
/// Gets objects from database with filting and paging.
/// </summary>
/// <param name= »filter »> Specified a filter </param>
/// <param name= »total »> Returns the total records count of the filter. </param>
/// <param name= »index »> Specified the page index. </param>
/// <param name= »size »> Specified the page size </param>
IQueryable<T> Filter(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 50);

/// <summary>
/// Gets the object(s) is exists in database by specified filter.
/// </summary>
/// <param name= »predicate »> Specified the filter expression </param>
bool Contains(Expression<Func<T, bool>> predicate);

/// <summary>
/// Find object by keys.
/// </summary>
/// <param name= »keys »> Specified the search keys. </param>
T Find(params object[] keys);

/// <summary>
/// Find object by specified expression.
/// </summary>
/// <param name= »predicate »> </param>
T Find(Expression<Func<T, bool>> predicate);

/// <summary>
/// Create a new object to database.
/// </summary>
/// <param name= »entity »> Specified a new object to create. </param>
T Create(T entity);

/// <summary>
/// Deletes the object by primary key
/// </summary>
/// <param name= »id »> </param>
void Delete(object id);

/// <summary>
/// Delete the object from database.
/// </summary>
/// <param name= »entity »> Specified a existing object to delete. </param>
void Delete(T entity);

/// <summary>
/// Delete objects from database by specified filter expression.
/// </summary>
/// <param name= »predicate »> </param>
void Delete(Expression<Func<T, bool>> predicate);

/// <summary>
/// Update object changes and save to database.
/// </summary>
/// <param name= »entity »> Specified the object to save. </param>
void Update(T entity);
/// <summary>
///
/// </summary>
/// <param name= »query »></param>
/// <param name= »parameters »></param>
/// <returns></returns>
IEnumerable<T> GetWithRawSql(string query, params object[] parameters);
}

  • Next, we are going to implement the IRepository interface

public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _dbContext;
protected readonly DbSet<T> _dbSet;

public Repository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
}

public virtual int Count
{
get { return _dbSet.Count(); }
}

public virtual IQueryable<T> All()
{
return _dbSet.AsQueryable();
}

public virtual T GetById(object id)
{
return _dbSet.Find(id);
}

public virtual IQueryable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = «  »)
{
IQueryable<T> query = _dbSet;

if (filter != null)
{
query = query.Where(filter);
}

if (!String.IsNullOrWhiteSpace(includeProperties))
{
foreach (var includeProperty in includeProperties.Split(new[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}

if (orderBy != null)
{
return orderBy(query).AsQueryable();
}
else
{
return query.AsQueryable();
}
}

public virtual IQueryable<T> Filter(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate).AsQueryable();
}

public virtual IQueryable<T> Filter(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 50)
{
int skipCount = index * size;
var resetSet = filter != null ? _dbSet.Where(filter).AsQueryable() : _dbSet.AsQueryable();
resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
total = resetSet.Count();
return resetSet.AsQueryable();
}

public bool Contains(Expression<Func<T, bool>> predicate)
{
return _dbSet.Count(predicate) > 0;
}

public virtual T Find(params object[] keys)
{
return _dbSet.Find(keys);
}

public virtual T Find(Expression<Func<T, bool>> predicate)
{
return _dbSet.FirstOrDefault(predicate);
}

public virtual T Create(T entity)
{
var newEntry = _dbSet.Add(entity);
return newEntry;
}

public virtual void Delete(object id)
{
var entityToDelete = _dbSet.Find(id);
Delete(entityToDelete);
}

public virtual void Delete(T entity)
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}

public virtual void Delete(Expression<Func<T, bool>> predicate)
{
var entitiesToDelete = Filter(predicate);
foreach (var entity in entitiesToDelete)
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
}

public virtual void Update(T entity)
{
var entry = _dbContext.Entry(entity);
_dbSet.Attach(entity);
entry.State = EntityState.Modified;
}

public virtual IEnumerable<T> GetWithRawSql(string query, params object[] parameters)
{
return _dbSet.SqlQuery(query, parameters).ToList();
}
}

  • Lets create a IDbContextFactory interface  interface and implement it

Hash1png

We will use the DBContextFactory interface to handle multiple database or schemas, for example if a database contains multiple schemas, we will have the opportunity to work with multiple schemas within a single context.

  • Lets create a IUnitOfWork interfaceand implement it

Hash2

IUnitOfWork  interface will be used only to get Repositories, save context and finally  dispose objectsHash3

B. Implementation of MembershipProvider

Our CustomMembershipProvider derives from  MembershipProvider

The first thing we are doing is to override Initialize(string name, NameValueCollection config) so as to get config parameters and also get ApplicationId or create it if does not exist

Hash5

Try it :

public override void Initialize(string name, NameValueCollection config)
{
// Initialize values from web.config.
if (config == null)
throw new ArgumentNullException(« config »);

// Initialize the abstract base class.
base.Initialize(name, config);

// Get application name
if (config["applicationName"] == null || config["applicationName"].Trim() == «  »)
{
ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
else
{
ApplicationName = config["applicationName"];
}

// Verify a record exists in the application table.
if ((_applicationId == Guid.Empty) || String.IsNullOrEmpty(_applicationName))
{
// Insert record for application.
if (_applicationId == Guid.Empty)
{
_applicationId = new MemberShipService().GetApplicationId(Guid.NewGuid(), _applicationName, String.Empty);
}
}
}

B.1  Encoding Password

Now lets create a random salt using SHA 512 string format CreateSalt512

In cryptography, a salt is random data that are used as an additional input to a one-way function that hashes a password or passphrase. The primary function of salts is to defend against dictionary attacks and pre-computed rainbow table attacks.

A new salt is randomly generated for each password. In a typical setting, the salt and the password are concatenated and processed with a cryptographic hash function, and the resulting output (but not the original password) is stored with the salt in a database. Hashing allows for later authentication while defending against compromise of the plaintext password in the event that the database is somehow compromised.

Hash6

Try it :

public static string RandomString(int size, bool lowerCase)
{
var builder = new StringBuilder();
var random = new Random();
for (int i = 0; i < size; i++)
{
char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return lowerCase ? builder.ToString().ToLower() : builder.ToString();
}
private static string CreateSalt512()
{
var message = RandomString(512,false);
return BitConverter.ToString((new SHA512Managed()).ComputeHash(Encoding.ASCII.GetBytes(message))).Replace(« - », «  »);
}

  • Now we will generate a hashed Password using our clear password and our resultes salt (secret key)

Hash7

Try it :

private string GenerateHMAC(string clearMessage, string secretKeyString)
{
var encoder = new ASCIIEncoding();
var messageBytes = encoder.GetBytes(clearMessage);
var secretKeyBytes = new byte[secretKeyString.Length / 2];
for (int index = 0; index < secretKeyBytes.Length; index++)
{
string byteValue = secretKeyString.Substring(index * 2, 2);
secretKeyBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
var hmacsha512 = new HMACSHA512(secretKeyBytes);

byte[] hashValue = hmacsha512.ComputeHash(messageBytes);

string hmac = «  »;
foreach (byte x in hashValue)
{
hmac += String.Format(« {0:x2} », x);
}

return hmac.ToUpper();
}

  • Now we ‘ll use the GenerateHMAC function to Hash password and put in on database table

Hash8

Try it :

public override MembershipUser GetUser(string username, bool userIsOnline)
{
// Please implement it : check if user exist or not on database
return null;
}

public override MembershipUser CreateUser(string username,string password,string email,string passwordQuestion,string passwordAnswer,
bool isApproved,
object providerUserKey,
out MembershipCreateStatus status)
{
status = MembershipCreateStatus.Success;

MembershipUser u = GetUser(username, false);

if (u == null)
{
DateTime createDate = DateTime.UtcNow;
string salt = CreateSalt512();

var user = new aspnet_Users
{
UserId = new Guid(providerUserKey.ToString()),UserName = username,LoweredUserName = username.ToLowerInvariant(),ApplicationId = _applicationId,
IsAnonymous = false,
LastActivityDate = createDate,
MobileAlias = null,

aspnet_Membership = new aspnet_Membership
{
ApplicationId = _applicationId,Comment = null,CreateDate = createDate,Email = email,IsApproved = isApproved,IsLockedOut = false,
LastLoginDate = createDate,FailedPasswordAnswerAttemptCount = 0,LastLockoutDate = _minDate,
LoweredEmail = (email != null ? email.ToLowerInvariant() : null),
MobilePIN = null,Password = GenerateHMAC(password, salt),FailedPasswordAnswerAttemptWindowStart = _minDate,
FailedPasswordAttemptCount = 0,FailedPasswordAttemptWindowStart = _minDate,LastPasswordChangedDate = createDate,
PasswordSalt = salt,PasswordFormat = (int)MembershipPasswordFormat.Hashed,PasswordQuestion = passwordQuestion
}

};

new MemberShipService().CreateUser(user);
return GetUser(username, false);
}
status = MembershipCreateStatus.DuplicateUserName;
return null;
}

  • Now lets implement  our operations  of  MemberShipService class :

Hash9

Try it :

public Guid GetApplicationId(Guid id, string applicationName, string description)
{
using (var unitOfWork = new UnitOfWork(new DbContextFactory<LogCornerSecurityContext>()))
{
// Returns Application id exist
string loweredApplicationName = applicationName.ToLowerInvariant();
var result = unitOfWork.GetRepository<aspnet_Applications>()
.Get(a => a.LoweredApplicationName == loweredApplicationName).FirstOrDefault();

// Create it if does not exist
if (result == null)
{

result = unitOfWork.GetRepository<aspnet_Applications>().Create(new aspnet_Applications
{
ApplicationId = id,
ApplicationName = applicationName,
Description = description,
LoweredApplicationName = applicationName.ToLowerInvariant()
});
unitOfWork.Save();
}
return result.ApplicationId;
}
}

public void CreateUser(aspnet_Users user)
{
using (var unitOfWork = new UnitOfWork(new DbContextFactory<LogCornerSecurityContext>()))
{
unitOfWork.GetRepository<aspnet_Users>().Create(user);
unitOfWork.Save();
}
}

  •  Run our sample application and enter user informations, so password is hashed and stored as follows :

Login informations

Hash10

Runtime values

Hash11

Database table [dbo].[aspnet_Membership] valuesHash12

So we can see that password is hashed according to salt and stored in database.

To better understand and right implement salt, please seek for more information about How Hashes are Cracked ?  what happen if hacker try to decode password ?

Before using Salt Password Hashing, we must understand what is Dictionary and Brute Force Attacks, Reverse Lookup Tables, Lookup Tables and Rainbow Tables.

B.2  << Matching >> Password

Now, to << decode >> the password (if one can speak of decoding) we can simply hash the password provided by the user with the basic salt stored on database and compare the resulting hash with the hash stored in the database.

So one and only the user knows the password. If any one else can discover the password then we are the victim of a successful attack.

The validate function can look like this

Untitled pictureTry it :

public override bool ValidateUser(string username, string password)
{
// Get the user so as to find Salt and Hashed Password
aspnet_Users user = new MemberShipService().GetUser(username, _applicationId);

if (user != null)
{
// hash the password provided by the user with the basic salt stored on database and compare
// the resulting hash with the hash stored in the database

bool isAuthenticated = (user.aspnet_Membership.Password == GenerateHMAC(password, user.aspnet_Membership.PasswordSalt));
if (isAuthenticated)
{
// If success, then update datetime login
user.LastActivityDate = DateTime.Now;
user.aspnet_Membership.LastLoginDate = DateTime.Now;
UpdateUser(user);
}
else
{
// If not logged then update failure account so as to lock user
UpdateFailureCount(username, « password », isAuthenticated);
}
return isAuthenticated;
}
return false;
}

Now, what can happen if clear password travels on networks before being encoded ?

We will see this topic at next tutorial

Regards

ASP.NET Web API using Cloud Service Bus Queues

In this article, we are going to walk through how to create, build  and deploy your Windows AZURE Cloud Service.

We will create a Cloud Service With ASP.NET Web API using web and worker roles. And finally we will introduce how to communicate between tiers using Service Bus Queues.

It also provides a good introduction on how to quickly  create and set up your Windows AZURE Cloud Service for deployment and Source Control Integration

For more information about your Windows AZURE Cloud Service, please take a look at documentation.

Is coming soon, fill in the form to get notified

Creating the Application Services Database for SQL Server

Mots-clés

, , , , ,

ASP.NET includes a tool for installing the SQL Server database used by the SQL Server providers, named Aspnet_regsql.exe. The Aspnet_regsql.exe tool is located in the drive:\WINDOWS\Microsoft.NET\Framework\versionNumber folder on your Web server. Aspnet_regsql.exe is used to both create the SQL Server database and add or remove options from an existing database.

You can run Aspnet_regsql.exe without any command line arguments to run a wizard that will walk you through specifying connection information for the computer running SQL Server and installing or removing the database elements for all the supported features. You can also run Aspnet_regsql.exe as a command-line tool to specify database elements for individual features to add or remove.

NoteNote
The database elements that are installed in the feature database will always be owned by the SQL Server database owner account (dbo). In order to install the feature database, a SQL Server login must be permitted to the db_ddladmin and dd_securityadmin roles for the SQL Server database. However, you do not need to be a system administrator for the SQL Server in order to install the feature database.

To run the Aspnet_regsql.exe wizard, run Aspnet_regsql.exe without any command line arguments, as shown in the following example:

C:\WINDOWS\Microsoft.NET\Framework\<versionNumber>\aspnet_regsql.exe

You can also run the Aspnet_regsql.exe tool as a command-line utility. For example, the following command installs the database elements for membership and role management on the local computer running SQL Server:

aspnet_regsql.exe -E -S localhost -A mr

The following table describes the command line options supported by the Aspnet_regsql.exe tool.

Option Description
-? Prints Aspnet_regsql.exe tool Help text in the command window.
-W Runs the tool in wizard mode. This is the default if no command line arguments are specified.
-C connection string The connection string to the computer running SQL Server where the database will be installed, or is already installed. This option is not necessary if you only specify the server (-S) and login (-U and -P, or -E) information.
-S server The name of the computer running SQL Server where the database will be installed, or is already installed. The server name can also include an instance name, such as .\INSTANCENAME.
-U login id The SQL Server user id to log in with. This option also requires the password (-P) option. This option is not necessary if you are authenticating using Windows credentials (-E).
-P password The SQL Server password to log in with. This option also requires the login id (-U) option. This option is not necessary if authenticating using Windows credentials (-E).
-E Authenticates using the Windows credentials of the currently logged-in user.
-d database The name of the database to create or modify. If the database is not specified, the default database name of « aspnetdb » is used.
-sqlexportonlyfilename Generates a SQL script file that can be used to add or remove the specified features. The specified actions are not performed.
-A all|m|r|p|c|w Adds support for one or more features. The following identifiers are used for ASP.NET features.

IdentifierAffects
allAll features
mMembership
rRole management
pProfile
cWeb Parts personalization
wWeb events

Feature identifiers can be specified together or separately, as shown in the following examples.

aspnet_regsql.exe -E -S localhost -A mp

aspnet_regsql.exe -E -S localhost -A m -A p

-R all|m|r|p|c|w Removes support for one or more features. The following identifiers are used for ASP.NET features.

IdentifierAffects
allAll features
mMembership
rRole management
pProfile
cWeb Parts personalization
wWeb events

Feature identifiers can be specified together or separately, as shown in the following examples.

aspnet_regsql.exe -E -S localhost -R mp

aspnet_regsql.exe -E -S localhost -R m -R p

-Q Runs the tool in quiet mode and does not confirm before removing a feature.

In this section , we can create our security database according to our business model and store it on sql server, oracle, mysql or other.

If you have already a security database, go to the next section.

Open visual studio prompt command tool and run command line aspnet_regsql as following

aspnetbd1

The screen explain the wizard scenario  so Click next

aspnetbd2

Here we can remove existing security database or create a new one.  We want to create a new security database. So check the first option and click next

aspnetbd3

Enter our database server name .\SQLEXPRESS  ( enter the appropriate server name).  if you already an existing database, you can select it. So the wizard will create the security tables on the selected datase.

If you do not have a database, let default. the default database name that will be created is aspnetdb

aspnetbd4

The wizard dispays the summary action, so click next to confirm  and finish the action

aspnetbd5aspnetbd6

Connect to sql server , locate aspnetdb database, expand tables, views, stored procedure.  you can now explore the default microsof security database business model.

aspnetbd7aspnetbd8

for more informations please visit msdn web site 

This tutorial  is the first of a series Mastering Custum ASP.NET MemberShip Provider using ASP.NET MVC , please see next  Introduction to entity framework database first

ASP.NET MVC Custom Membership Password Hashing based on SALT key using SHA-3 Algorithm

Mots-clés

, , , , , , , , , , , , ,

ASP.NET membership is designed to enable you to easily use a number of different membership providers for your ASP.NET applications. You can use the supplied membership providers that are included with the .NET Framework, or you can implement your own providers.

There are two primary reasons for creating a custom membership provider.

  • You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a MysQL database, an Oracle database, or other data sources.
  • You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

This tutorial  is a continuation of our tutorial  How to configure Custom Membership and Role Provider using ASP.NET MVC4

Let’s talk about password encoding and decoding and take the opportunity to introduce the Unit Of Work Pattern used to insert and retrieve data.

There exists a sequence of hash functions SHA-0, SHA-1, SHA-2 and the most recent SHA-3.

SHA-3, is a new cryptographic hash function that has been selected by NIST in October 2012 following a public competition launched in 2007, this because the weaknesses discovered on MD-5 and SHA-1 let fear fragility SHA-2 is built on the same schéma. It has variations that can produce hashes 224, 256, 384 and 512 bits. It is built on a different principle from that of MD5, SHA-1 and SHA-2 functions.

So in our tutorial, we will use the SHA-3  512 bits,

For this, it is not intended to replace SHA-2, which is at present not been compromised by a significant attack, but to provide an alternative response to attacks against MD5 possibilities standards SHA-0 and SHA-1.

A. Unit Of Work Pattern

The purpose of this article is not an introduction to Unit Of Work Pattern but a particular use of it. So for more information Unit Of Work Pattern, please read articles that deal with this subject such as http://msdn.microsoft.com/en-us/magazine/dd882510.aspx

  • Create a class library Project and reference EntityFramwork.dll
  • Generate the model and classes from membeship database (Model.Context.tt, Model.Entities.tt and Model.mapping.tt ) . If you are newly in Entity Framwork, please read our tutorial  Introduction to entity framework Code first
  • Create IRepository interface

public interface IRepository<T> where T : class
{
/// <summary>
/// Get the total objects count.
/// </summary>
int Count { get; }

/// <summary>
/// Gets all objects from database
/// </summary>
IQueryable<T> All();

/// <summary>
/// Gets object by primary key.
/// </summary>
/// <param name= »id »> primary key </param>
/// <returns> </returns>
T GetById(object id);

/// <summary>
/// Gets objects via optional filter, sort order, and includes
/// </summary>
/// <param name= »filter »> </param>
/// <param name= »orderBy »> </param>
/// <param name= »includeProperties »> </param>
/// <returns> </returns>
IQueryable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = «  »);

/// <summary>
/// Gets objects from database by filter.
/// </summary>
/// <param name= »predicate »> Specified a filter </param>
IQueryable<T> Filter(Expression<Func<T, bool>> predicate);

/// <summary>
/// Gets objects from database with filting and paging.
/// </summary>
/// <param name= »filter »> Specified a filter </param>
/// <param name= »total »> Returns the total records count of the filter. </param>
/// <param name= »index »> Specified the page index. </param>
/// <param name= »size »> Specified the page size </param>
IQueryable<T> Filter(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 50);

/// <summary>
/// Gets the object(s) is exists in database by specified filter.
/// </summary>
/// <param name= »predicate »> Specified the filter expression </param>
bool Contains(Expression<Func<T, bool>> predicate);

/// <summary>
/// Find object by keys.
/// </summary>
/// <param name= »keys »> Specified the search keys. </param>
T Find(params object[] keys);

/// <summary>
/// Find object by specified expression.
/// </summary>
/// <param name= »predicate »> </param>
T Find(Expression<Func<T, bool>> predicate);

/// <summary>
/// Create a new object to database.
/// </summary>
/// <param name= »entity »> Specified a new object to create. </param>
T Create(T entity);

/// <summary>
/// Deletes the object by primary key
/// </summary>
/// <param name= »id »> </param>
void Delete(object id);

/// <summary>
/// Delete the object from database.
/// </summary>
/// <param name= »entity »> Specified a existing object to delete. </param>
void Delete(T entity);

/// <summary>
/// Delete objects from database by specified filter expression.
/// </summary>
/// <param name= »predicate »> </param>
void Delete(Expression<Func<T, bool>> predicate);

/// <summary>
/// Update object changes and save to database.
/// </summary>
/// <param name= »entity »> Specified the object to save. </param>
void Update(T entity);
/// <summary>
///
/// </summary>
/// <param name= »query »></param>
/// <param name= »parameters »></param>
/// <returns></returns>
IEnumerable<T> GetWithRawSql(string query, params object[] parameters);
}

  • Next, we are going to implement the IRepository interface

public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _dbContext;
protected readonly DbSet<T> _dbSet;

public Repository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
}

public virtual int Count
{
get { return _dbSet.Count(); }
}

public virtual IQueryable<T> All()
{
return _dbSet.AsQueryable();
}

public virtual T GetById(object id)
{
return _dbSet.Find(id);
}

public virtual IQueryable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = «  »)
{
IQueryable<T> query = _dbSet;

if (filter != null)
{
query = query.Where(filter);
}

if (!String.IsNullOrWhiteSpace(includeProperties))
{
foreach (var includeProperty in includeProperties.Split(new[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}

if (orderBy != null)
{
return orderBy(query).AsQueryable();
}
else
{
return query.AsQueryable();
}
}

public virtual IQueryable<T> Filter(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate).AsQueryable();
}

public virtual IQueryable<T> Filter(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 50)
{
int skipCount = index * size;
var resetSet = filter != null ? _dbSet.Where(filter).AsQueryable() : _dbSet.AsQueryable();
resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
total = resetSet.Count();
return resetSet.AsQueryable();
}

public bool Contains(Expression<Func<T, bool>> predicate)
{
return _dbSet.Count(predicate) > 0;
}

public virtual T Find(params object[] keys)
{
return _dbSet.Find(keys);
}

public virtual T Find(Expression<Func<T, bool>> predicate)
{
return _dbSet.FirstOrDefault(predicate);
}

public virtual T Create(T entity)
{
var newEntry = _dbSet.Add(entity);
return newEntry;
}

public virtual void Delete(object id)
{
var entityToDelete = _dbSet.Find(id);
Delete(entityToDelete);
}

public virtual void Delete(T entity)
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}

public virtual void Delete(Expression<Func<T, bool>> predicate)
{
var entitiesToDelete = Filter(predicate);
foreach (var entity in entitiesToDelete)
{
if (_dbContext.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
}

public virtual void Update(T entity)
{
var entry = _dbContext.Entry(entity);
_dbSet.Attach(entity);
entry.State = EntityState.Modified;
}

public virtual IEnumerable<T> GetWithRawSql(string query, params object[] parameters)
{
return _dbSet.SqlQuery(query, parameters).ToList();
}
}

  • Lets create a IDbContextFactory interface  interface and implement it

Hash1png

We will use the DBContextFactory interface to handle multiple database or schemas, for example if a database contains multiple schemas, we will have the opportunity to work with multiple schemas within a single context.

  • Lets create a IUnitOfWork interfaceand implement it

Hash2

IUnitOfWork  interface will be used only to get Repositories, save context and finally  dispose objectsHash3

B. Implementation of MembershipProvider

Our CustomMembershipProvider derives from  MembershipProvider

The first thing we are doing is to override Initialize(string name, NameValueCollection config) so as to get config parameters and also get ApplicationId or create it if does not exist

Hash5

Try it :

public override void Initialize(string name, NameValueCollection config)
{
// Initialize values from web.config.
if (config == null)
throw new ArgumentNullException(« config »);

// Initialize the abstract base class.
base.Initialize(name, config);

// Get application name
if (config["applicationName"] == null || config["applicationName"].Trim() == «  »)
{
ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
else
{
ApplicationName = config["applicationName"];
}

// Verify a record exists in the application table.
if ((_applicationId == Guid.Empty) || String.IsNullOrEmpty(_applicationName))
{
// Insert record for application.
if (_applicationId == Guid.Empty)
{
_applicationId = new MemberShipService().GetApplicationId(Guid.NewGuid(), _applicationName, String.Empty);
}
}
}

B.1  Encoding Password

Now lets create a random salt using SHA 512 string format CreateSalt512

In cryptography, a salt is random data that are used as an additional input to a one-way function that hashes a password or passphrase. The primary function of salts is to defend against dictionary attacks and pre-computed rainbow table attacks.

A new salt is randomly generated for each password. In a typical setting, the salt and the password are concatenated and processed with a cryptographic hash function, and the resulting output (but not the original password) is stored with the salt in a database. Hashing allows for later authentication while defending against compromise of the plaintext password in the event that the database is somehow compromised.

Hash6

Try it :

public static string RandomString(int size, bool lowerCase)
{
var builder = new StringBuilder();
var random = new Random();
for (int i = 0; i < size; i++)
{
char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return lowerCase ? builder.ToString().ToLower() : builder.ToString();
}
private static string CreateSalt512()
{
var message = RandomString(512,false);
return BitConverter.ToString((new SHA512Managed()).ComputeHash(Encoding.ASCII.GetBytes(message))).Replace(« - », «  »);
}

  • Now we will generate a hashed Password using our clear password and our resultes salt (secret key)

Hash7

Try it :

private string GenerateHMAC(string clearMessage, string secretKeyString)
{
var encoder = new ASCIIEncoding();
var messageBytes = encoder.GetBytes(clearMessage);
var secretKeyBytes = new byte[secretKeyString.Length / 2];
for (int index = 0; index < secretKeyBytes.Length; index++)
{
string byteValue = secretKeyString.Substring(index * 2, 2);
secretKeyBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
var hmacsha512 = new HMACSHA512(secretKeyBytes);

byte[] hashValue = hmacsha512.ComputeHash(messageBytes);

string hmac = «  »;
foreach (byte x in hashValue)
{
hmac += String.Format(« {0:x2} », x);
}

return hmac.ToUpper();
}

  • Now we ‘ll use the GenerateHMAC function to Hash password and put in on database table

Hash8

Try it :

public override MembershipUser GetUser(string username, bool userIsOnline)
{
// Please implement it : check if user exist or not on database
return null;
}

public override MembershipUser CreateUser(string username,string password,string email,string passwordQuestion,string passwordAnswer,
bool isApproved,
object providerUserKey,
out MembershipCreateStatus status)
{
status = MembershipCreateStatus.Success;

MembershipUser u = GetUser(username, false);

if (u == null)
{
DateTime createDate = DateTime.UtcNow;
string salt = CreateSalt512();

var user = new aspnet_Users
{
UserId = new Guid(providerUserKey.ToString()),UserName = username,LoweredUserName = username.ToLowerInvariant(),ApplicationId = _applicationId,
IsAnonymous = false,
LastActivityDate = createDate,
MobileAlias = null,

aspnet_Membership = new aspnet_Membership
{
ApplicationId = _applicationId,Comment = null,CreateDate = createDate,Email = email,IsApproved = isApproved,IsLockedOut = false,
LastLoginDate = createDate,FailedPasswordAnswerAttemptCount = 0,LastLockoutDate = _minDate,
LoweredEmail = (email != null ? email.ToLowerInvariant() : null),
MobilePIN = null,Password = GenerateHMAC(password, salt),FailedPasswordAnswerAttemptWindowStart = _minDate,
FailedPasswordAttemptCount = 0,FailedPasswordAttemptWindowStart = _minDate,LastPasswordChangedDate = createDate,
PasswordSalt = salt,PasswordFormat = (int)MembershipPasswordFormat.Hashed,PasswordQuestion = passwordQuestion
}

};

new MemberShipService().CreateUser(user);
return GetUser(username, false);
}
status = MembershipCreateStatus.DuplicateUserName;
return null;
}

  • Now lets implement  our operations  of  MemberShipService class :

Hash9

Try it :

public Guid GetApplicationId(Guid id, string applicationName, string description)
{
using (var unitOfWork = new UnitOfWork(new DbContextFactory<LogCornerSecurityContext>()))
{
// Returns Application id exist
string loweredApplicationName = applicationName.ToLowerInvariant();
var result = unitOfWork.GetRepository<aspnet_Applications>()
.Get(a => a.LoweredApplicationName == loweredApplicationName).FirstOrDefault();

// Create it if does not exist
if (result == null)
{

result = unitOfWork.GetRepository<aspnet_Applications>().Create(new aspnet_Applications
{
ApplicationId = id,
ApplicationName = applicationName,
Description = description,
LoweredApplicationName = applicationName.ToLowerInvariant()
});
unitOfWork.Save();
}
return result.ApplicationId;
}
}

public void CreateUser(aspnet_Users user)
{
using (var unitOfWork = new UnitOfWork(new DbContextFactory<LogCornerSecurityContext>()))
{
unitOfWork.GetRepository<aspnet_Users>().Create(user);
unitOfWork.Save();
}
}

  •  Run our sample application and enter user informations, so password is hashed and stored as follows :

Login informations

Hash10

Runtime values

Hash11

Database table [dbo].[aspnet_Membership] valuesHash12

So we can see that password is hashed according to salt and stored in database.

To better understand and right implement salt, please seek for more information about How Hashes are Cracked ?  what happen if hacker try to decode password ?

Before using Salt Password Hashing, we must understand what is Dictionary and Brute Force Attacks, Reverse Lookup Tables, Lookup Tables and Rainbow Tables.

B.2  << Matching >> Password

Now, to << decode >> the password (if one can speak of decoding) we can simply hash the password provided by the user with the basic salt stored on database and compare the resulting hash with the hash stored in the database.

So one and only the user knows the password. If any one else can discover the password then we are the victim of a successful attack.

The validate function can look like this

Untitled pictureTry it :

public override bool ValidateUser(string username, string password)
{
// Get the user so as to find Salt and Hashed Password
aspnet_Users user = new MemberShipService().GetUser(username, _applicationId);

if (user != null)
{
// hash the password provided by the user with the basic salt stored on database and compare
// the resulting hash with the hash stored in the database

bool isAuthenticated = (user.aspnet_Membership.Password == GenerateHMAC(password, user.aspnet_Membership.PasswordSalt));
if (isAuthenticated)
{
// If success, then update datetime login
user.LastActivityDate = DateTime.Now;
user.aspnet_Membership.LastLoginDate = DateTime.Now;
UpdateUser(user);
}
else
{
// If not logged then update failure account so as to lock user
UpdateFailureCount(username, « password », isAuthenticated);
}
return isAuthenticated;
}
return false;
}

Now, what can happen if clear password travels on networks before being encoded ?

We will see this topic at next tutorial

Regards

Create , Build and Deploy your windows AZURE Cloud Service

Mots-clés

, , , , , ,

In this article, we are going to walk through how to create  and deploy your Windows AZURE Cloud Service.

It also provides a good introduction on how to quickly  create and set up your Windows AZURE Cloud Service for deployment and Source Control Integration

For more information about your Windows AZURE Cloud Service, please take a look at documentation.

A. CREATE AN ACCOUNT

  • The first step is to connect to http://www.windowsazure.com/  and create an account. it is possible to try windows AZURE for 3 months for which have not yet an account.

If you already have an account, connect by clicking on PORTAL

CloudService1

B. CREATE A SERVICE CLOUD

  • Click on CLOUD SERVICE tab and  Click New (+ New)

CloudService2

Here it is possible to create a Quick Cloud Service and configure it again later or create a custom cloud service by chosing configuration.

  • So lets create a Quick Cloud Service and fill parameters such as URL, REGION OR AFFINITY GROUP , SUBSCRIPTION. Next click on link Create Cloud Service

NB : for REGION OR AFFINITY GROUP, we chose West Europe because our subscription is located there.  we would have to pay data transfer if we had chosen another location.

CloudService25

Note : For those who want to create a custom cloud service, the procedure is as follows :

It is possible to create your cloud service by specifying a URL and deploying a package to the staging or production environment.

tfs3

tfs4

Our Cloud Service is now created Quickly or Customized, lets get Azure SDK Tools so as to code our service logic.

  • Click on ProductService, click on link install a Windows AZURE SDK, and our Visual Studio Version and Install it.

CloudService4

CloudService5

C. CREATE A CLOUD SERVICE PROJECT

Here we are going to create a WCF Service and deploy it on our cloud Service.

  • So, create a new Project ,chose Windows Azure Cloud Service template and WCF Service Web Role.

web role provides an environment for running web sites or applications as supported by Internet Information Services (IIS) 7.0

CloudService6

CloudService7

CloudService8

  • Implement a simple WCF web Service (ProductService.svc) and test it on local as follows :

CloudService9

CloudService26

CloudService27

CloudService28

D. DEPLOY A CLOUD SERVICE PROJECT

  • To deploy our Cloud Service, we have to Create a Package : chose our Service Configuration and Build Configuration and note the output directory or remove files to our custom directory.

CloudService13

CloudService14

CloudService15

  • Next , Go back again to our Portal, click on ProductService,  and click on link New production deployment

CloudService29

  • Next  chose a deployment name and our Package and configuration files

CloudService30

CloudService31

  • Now reference our Cloud Service and test It

CloudService32

CloudService33CloudService34

E. DEPLOY A CLOUD SERVICE PROJECT USING TEAM FOUNDATION SERVER

In this step, we are going to deploy our service using Team Foundation Services. With Team Foundation Service, you have an ALM solution from end to end, based on the cloud, which handles everything from version control and code review in the planning and design. Better yet, you can access virtually anywhere.

To create an account on team foundation services, simply go to http://tfs.visualstudio.com/, register and create your account.
Then you have a TFS Environmental Monitoring in the cloud for free 5 developers

tfs1

tfs2

For more information about Team Foundation Services Pricing please visit http://tfs.visualstudio.com/pricing/tfs-information

  • Click on link Setup TFS publishing

CloudService35Here, we can create  a new TFS Account or use an existing account.CloudService36

  • Chose our Team Collection BlogCloudService38 CloudService40
  • Now Open Visual Studio and Add our Project to Source Control (Use Team Collection Blog)

CloudService39

Ok, Our TFS Configuration is now ready. After each Check In TFS will build our Service and deploy it to Windows AZURE

  • To test our TFS deployment please update our service to add new product

CloudService41

  • Check our modification to  Source Control

CloudService42

  • The build is started

CloudService43

  • Wait fot the build to complete and run our console applicaction

CloudService44We are at the end of the  tutorial.

Regards

Suivre

Recevez les nouvelles publications par mail.

Rejoignez 641 autres abonnés