Question

ASP.net C# - How do I default the User Name to the Login control when users select Remember Me?

Asked by: Bryav

I have a strange requrement twist on the Login RememberMe function.  When a user selects RememberMe on the Login Control, I have to default in the User Name and check the RememberMe box.  Upon Login, if they de-select the checkbox, then stop defaulting in the User Name and uncheck the RememberMe box.  

The idea is that the user will always be required to type in thier password in order to log in.  I've tried several variations of using either the membership or cookies, but then have an issue with how to log out or de-authenticate the user while keeping the cookies.  

If I do a FormsAuthentication.SignOut(); I lose the authentication ticket, so I was trying to do a HttpContext.Current.Session.Abandon(); and then just look for the cookie.

I can set the text box properties and remember me properties of the Login control using this code:
TextBox un = (TextBox)Login1.FindControl("UserName");
                un.Text = rmCookie["RememberMe"];
                Login1.RememberMeSet = true;
But if you try to put this in the page OnLoad event you get stuck and can't login - I believe that's because it's causing a changed event on the textbox.

None of the things I've tried have worked.  i'm thinking that surely someone out there has done something like this and it's fairly simple.

Any ideas on how to make something like this work?  

I'm doing aspx.cs (code behind) with an asp.net 2.0 Login control.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-06-25 at 23:32:32ID22657556
Topics

Microsoft Visual C#.Net

,

C# Programming Language

,

.NET Framework 2.x

Participating Experts
4
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ASP.Net and Javascript variable OnLoad
    I have the following Javascript: <script language="JavaScript"> <!--hide from old browsers var time = null function move() { window.location = 'http://www.abc.com' } //--> </script> In my HTML body I have: onload="timer=setT...
  2. asp.net login
    Hi there I was wondering if there is any way I can get client information on an intranet at work, I've seen this in work and I am identified if i open certain work webpages. I am making a web app for some workers but don't want to submit login information in the url string. T...
  3. asp.net login
    I used asp.net 2.0 with C# and create very simple login screen and point to the sql database to check validation. After validation is completed, I want to create session variable from the login. so the whole application can use the session for security issue. How can I do t...
  4. ASP.Net body onload event with master pages
    Hi Am using asp.net 3.5 with master pages. I need to run some javascript to preload some images in the body onload event but I don't need to run this on every page. The only body tag is in the master page (mp.master) for the site so currently the event runs for all conten...
  5. Form authentication persistant cookie/ticket not working
    My original code for creating a persistant Forms authentication cookie/ticket used to work perfectly before. However, (I believe) as a result of the recent upgrade to .NET Framework 3.5, it has stopped working and I have lots of people at work mad at me since their cookie exp...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mmarinovPosted on 2007-06-26 at 00:35:52ID: 19361487

Hello Bryav,

Have you checked this article: http://msdn2.microsoft.com/en-us/library/ms178340.aspx ?
There are very good descriptions of the abilities of the Login control

Regards,
mmarinov

 

by: steelheart38Posted on 2007-06-26 at 02:30:01ID: 19361989

are you using the cookie created by FormsAuthentication?

it might be possible to use your own cookie instead. In that way, even if you call FormsAuthentication.SignOut, it won't remain.

It looks like your on the right track but not sure what this means by "you get stuck and can't login - I believe that's because it's causing a changed event on the textbox."

 

by: TheLearnedOnePosted on 2007-06-26 at 03:13:49ID: 19362223

I think this is what Martin was talking about:

<Quote>
If you want the control to display a Remember me next time check box, set the DisplayRememberMe property to true. If a user selects the Remember me next time check box when he or she logs in, the authentication token will be stored in a persistent cookie in the browser.
</Quote>

Bob

 

by: BryavPosted on 2007-06-26 at 05:58:34ID: 19363168

Yes, I've looked at that article and others like it.  The problem is that what I have to do isn't "standard".  Normally, Forms authentication want's to log you in automatically, like it does on this site at Experts-Exchange.

In our case, we don't want it to actuallly log the user in (it's okay for them to authenticate using standard forms authentication) but they can't get to the application until they supply thier password and click the login button.

This is the scenario where I've been running into trouble.  When I try to use forms authentication, the problems comes when the user logs out.  They're technically still authenticated, just not to the app.  So if I use only the authentication ticket, there will be one whether there's a cookie or not and the user name will display even though they haven't selected to "remember me".

Things seem to work fine if you just login, close down the browser and come back.  But when you log out and go back to the default public page, I'm always getting finding either the cookie or the auth ticket from the previous session.

My thought was to just write a cookie with the username in it, then check for the presense of the cookie and throw the username into the Login box.  I just haven't been able to get this to work and beginning to think that I should just bite the bullet and code the complete login component as custom rather than using the 2.0 Login control.

I just hoped there'd be an easier way that that.  

My other thought was to just store a "remember me" flag in SQL Server then when the user authenticates via the authentication ticket - read the data field to see if they want to be remembered.  I'd really like to avoid making a db change for this though, if I can avoid it.

I hope that clarifies things a bit more.  Let me know if you have more specific questions.

The proper question might be what code should be written to log the user out so they clear all the cookies from memory, clear the session variables, and establish a new session?  If I could do all that properly, then the default process from the Login control would work.  But if you do a FormsAuthentication.LogOut() it destroys the persistent ticket.

Thanks for the feedback everyone.  I wish it were simple, but then I wouldn't have needed to post the question.

Bryant

 

by: BryavPosted on 2007-06-26 at 06:50:38ID: 19363624

Let me give an example of what I've been running into.

Say I sign in and select the rememberMe check box from the Login control.  I get a persistent cookie with the authentication ticket inside.

Now if I add the following code:
MembershipUser mu = Membership.GetUser();
            TextBox un = (TextBox)Login1.FindControl("UserName");
            if (mu.UserName != null)
            {
                un.Text = mu.UserName;
                Login1.RememberMeSet = true;
            }

The login control has my username filled in and the rememberme box is checked.

There is no other code in entire login.ascx.cs file

But when I type my password and click login it doesn't go anywhere.  This same behavior occurs whether I put the code (listed above) in the Page_Load or in the Login_Init.

The login control is defined as follows:
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/App/AccountSummary.aspx" FailureText="We're sorry, but the username and password you entered could not be authenticated by our system." OnLoggedIn="OnLoggedIn" Width="201px" OnLoginError="OnLoginError" OnPreRender="Login1_PreRender" OnInit="Login1_Init">

The login button is as follows:
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Sign in" ValidationGroup="ctl00$Login1" TabIndex="4" CssClass="SignInButton" Style="border-color:White;border-width:1px;border-style:Outset;font-family:Arial;font-size:8pt;height:20px;width:75px;" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />

If I uncheck the Remember Me box and watch my temporary internet files, the cookie / auth ticket is removed.  If if check and sign in again, the cookie/auth ticket is there again.  The problem is that it doesn't ever get me to my app/AccountSummary.aspx page.

If I remove the code everthing works normally, but I don't have my username and remember me pre-filled in.

Any suggestions would be welcome.

Thanks,

Bryant

 

by: rugu_16Posted on 2007-06-26 at 14:04:38ID: 19367828

okay so first of all u r are using form authantication not windows so once you log out you logout...how will user stay logged in...he wont.....second you want to display user name before user app access your DB so database is out of question. Only way is cookies....see think about it....if i login and check the remmeber me checkbox then your app should create a cookie and save it on my machien....so next time when i open your webpage....on the page load you should access my pc and retrive that cookie value.....NOW you can set cookie life to whatever you want....so say if you set your cookie life to forever or couple of year then it will nto expire. ONLY when user will cean their brower history then cookie will be gone but that is true in any scenario.

 

by: BryavPosted on 2007-06-27 at 06:34:26ID: 19372043

You're right about having to definitely go with Cookies.  And you're correct

So here's what I've discovered and it leads me to the conclusion that I'm going to indeed have to write my own custom login component/control because the asp.net 2.0 Login Control won't let you set the username text field.

I got down to the basic problem I was having and tested it very simply.  Here's what I did:

I took the following code and pasted it one-at-a-time into each of the following Login Control events.
OnDataBinding
OnInit
OnLoad
OnPreRender
I also tried the same events on the UserName TextBox control within the Login control.
I further tried the code in the Page_Load event

Here's the code I used:
TextBox un = (TextBox)Login1.FindControl("UserName");
un.Text = "TestUser";

This simply finds the the text box in the Login control and sets it to a username - very simple.
I setup the TestUser account and ensured I was able to properly login using that username before I began my test.

The result is that no matter what event I placed that code to populate the username, I could not log in.  The Login control gets stuck in some sort of loop and won't fire of the LoggingIn or LoggedIn event.  It gives no errors and doesn't even fire off the OnLoginError event.

The net result was that it appears to the user as if they never hit the Sign In button.  In debug mode, the Login control seems to Load the Page multiple times and initialize a number of times, then just simply stops.  I also noticed that at some point it clears out the username and password, then fires the various event I had my code in, and repopulates the username from my code.

So my choice is to either write a custom login or possibly use the OnAuthenticate event or the OnClick event of the Sign In button to manually code the authentication and login logic.

This appears to be a bug in the Login control.  Can anyone else confirm this, or have any other suggestions?  I don't know if the Login.UserName method can be overridden to add a set. Currently it's read only.  Perhaps if I were able to do an override, and set the UserName field that way instead of through the text box, it would work.  Any thoughts out there?

Thanks again for the feedback.

Bryant

 

by: steelheart38Posted on 2007-06-27 at 20:36:32ID: 19378015

i could not pinpoint exactly what is causing the issue your describing. but i have to say that i have seen or worked on a working implementation of this (however for confidentiality reasons i couldn't post the whole code). that is, set the username of logincontrol and use custom cookies to store the username and remember me (used non formsAuthentication created cookies). if i'm not mistaken, it is the password textbox/field that cannot be set from code. the username and remember me can be set fine and once they are rendered to the browser it's as if the user entered them manually and clicking the login should behave properly (unless maybe some other manipulations are made i.e. textbox is disabled et al).

i believe you have a work around already but this is just for info. but might worth looking into if you have time as there may be something in code or settings that causes this issue and might get you into trouble even with a custom implementation of login

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...