Showing posts with label User Management. Show all posts
Showing posts with label User Management. Show all posts

Wednesday, August 1, 2012

Logout User In Asp.net Membership

While developing usermanagement based web application using Membership provider, many times we come across some trivial issues or queries as follows
  • formsauthentication.signout not working
  • Using formsauthentication.signout
  • logout user programmatically
  • Check user date subscription and log out if user is not valid.
  • programmatically logout in asp net
  • Logout user in asp.net Membership
Solution for all above queries is as follows
FormsAuthentication.SignOut();
  Session.Abandon();

 // clear authentication cookie
 HttpCookie frmcookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
 frmcookie.Expires = DateTime.Now.AddYears(-1);
 Response.Cookies.Add(frmcookie);

 // clear session cookie if we use any
 HttpCookie sessioncookie = new HttpCookie("ASP.NET_SessionId", "");
 sessioncookie.Expires = DateTime.Now.AddYears(-1);
 Response.Cookies.Add(sessioncookie);

 FormsAuthentication.RedirectToLoginPage("v=SubscriptionExpired");
Above code signout the user, remove all the Cookies set. Forms Authentication.RedirectToLoginPage uses settings in web.config file. We can pass Querystring to the function so that we can show proper Messages.
Submit this story to DotNetKicks

Read more...

Sunday, November 20, 2011

Access userName asp.net-membership without using Membership.getUser()

While I was working on Membership and User Management in Asp.Net 2010
Following Scenario
  • After creating user, admin sets subscribtion for the user.
  • User logs in with id and password, after validating user, I check for subscription details.
  • If user is logging in with subscription period he/she has access to the application else he/she will be redirected to Subscription Expired page.
To check subscription, I had requirement to get username and check it in Subscription table.
I did not want to use getUser function, as I just wanted to get user name of currently logged in user.

To get user name I used following line of code

System.Web.HttpContext.Current.User.Identity.Name


Submit this story to DotNetKicks

Read more...

Tuesday, November 8, 2011

Use Membership for user management - Basics

In this article we shall discuss the membership feature in ASP.NET applications. Asp.net has reduced the development drastically by introducing this. Membership feature of Asp.Net drastically reduces the amount of code we have to write to authenticate users at our Web site. In this article we are going to develop User Management system membership class, and SqlMembershipProvider.

Membership feature of Asp.net provides a membership API that simplifies the task of validating user credentials. SqlMembershipProvider uses SQL Database for storing membership details.

Step1: Install Membership Database for SQLMembershipProvider.
To install Membership Database we have to log on to our server with an account that has authority to administer SQL server. After this open Visual Studio 2010 Command prompt.


Run following command
aspnet_regsql.exe -E -S localhost -A m

Where:
    -E indicates authenticate using the Windows credentials of the currently logged on user.
    -S (server) indicates the name of the server where the database will be installed or is already installed.
    -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

Above command mainly generates database naming "aspnetdb" with following  schema structure and related stored procedures


* Please Note that Related stored procedures also get created with above command. These stored procedures get called internally from Membership provider. 

Step2: Configure Forms Authentication
Set following authentication mode in Web.config file
<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 
           protection="All" 
           timeout="30" 
           name="AppNameCookie" 
           path="/FormsAuth" 
           requireSSL="false" 
           slidingExpiration="true" 
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>

If so many options are not required we can simply use following Tag for authentication

<authentication mode="Forms">
      <forms loginUrl="Login.aspx" timeout="2880" />
    </authentication>

Add the following <authorization> element after the element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.


<authorization> 
   <deny users="?" />
   <allow users="*" />
</authorization>
  
Step 3: Configuring SQLMembership Provider
In Step 1, we created SQL Database for Membership Provider, in this step we will configure SQLMembership Provider in Web.config file.


<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
...
  <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    <providers>
      <clear />
      <add 
        name="SqlProvider" 
        type="System.Web.Security.SqlMembershipProvider" 
        connectionStringName="MyConnectionString"
        applicationName="/"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="true"
        requiresUniqueEmail="true"
        passwordFormat="Hashed" />
    </providers>
  </membership>

Default passwordFormat is "Hashed", if we remove it from Configuration then by default Passwords are stored in Hashed format. We can change passwordFormat to Encrypted. (This is not the scope of this Article; I shall put another article for it.)

Step 4: Start using Membership class
Upto step 3 we were only doing configuration for using Membership class. After we done with step 3; whenever we use Membership class, if by default uses Database structure generated in Step 1. It internally manages all the Database calls.
e.g.
Membership.CreateUser("UserName","Password");
//This will create user in Database.
Check out following Membership APIs for user management in Asp.net.
MethodParametersNotes
CreateUserstring username–User name to create.

string password–Password for new user


string email–E-mail for new user.

string passwordQuestion

string passwordAnswer

bool IsApproved

object providerUserKey
Used to create a new user.
DeleteUserstring username–User to delete.

bool removeAllRelatedData
Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
FindUsersByNamestring usernameToMatch

int pageIndex

int pageSize
Returns a collection of users where the string parameter passed matches part of the username.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
FindUsersByEmailstring emailToMatch

int pageIndex

int pageSize
Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.

Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
GeneratePasswordint length

Int numberOfNonAlpha

NumericCharacters
Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
GetAllUsersint pageIndex

int pageSize
Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
GetNumberOfUsersOnlineNoneReturns a count of all the users who are currently online

The Active Directory provider does not implement this functionality
GetUsernameByEmailstring email–Email of user to lookup.Return a member's username.
UpdateUserMembershipUser user–Membership user to updateUpdates a member's properties; for example, an e-mail address.
ValidateUserstring username–User name to validate.

string password–User password to validate.
Validates a user's credentials. Returns true if the credentials are valid and false if they are not.


With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.
(Note: Above table is picked up from MSDN)

This is how we can use Membership class for User management in Asp.net using SQLMembershipProvider.

Submit this story to DotNetKicks

Read more...