Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

Using Basic Forms Authentication in ASP.NET

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
[Microsoft ASP.NET] [] In this video, I'm going to show you how to use basic forms-based authentication programmatically with ASP.NET. So to get started, I'll fire up Visual Web Developer, and I'm going to open an existing project. Don't worry—this is really an empty project, and normally I start from scratch, but I want to use this empty project so that I can demonstrate doing authentication in as real-world a scenario as possible. So when I bundle up the code for you to download, you'll be able to download the empty standalone project just as it is as you're looking at it here before we started writing any code as well as the finished code that implements the forms-based authentication. So what you can see here in our master page is we've got some universal navigation links on the left and some universal boxes on the right and a header section, and this will be included in every derived page that uses this master page. If we go in and look at the source momentarily, you can see we have a placeholder in the header section that we won't actually be using for the purposes of this demo, and then here we've got the column on the— well, actually this is the header section— this TD right here is where we're going to implement our universal log-in logic that'll be in the header section of every derived page that uses this master page. Here in this TD I've just got a little bit of Java Script logic that gets the current date and displays that as well. Here you can see— in this TD here—these are the navigation boxes that are on the left-hand side of the page. Down at the bottom here, you can see the information boxes that are on the right-hand side of the page, and then here—this TD in the center—which is defined as 50% of the total width— this is the content placeholder for the main content area, and that is where the content in the derived page will go. So then I have a default .ASPX page, and you can see here that we're using the master page that we've just created, and there's really nothing special here. If we look at the content, we've just got 3 divs— the first 2 using one class, the center one using a different class for alternating styles— and some junk text—that's it. So if we go ahead and run this and just see what it looks like before we start adding the specific authentication stuff, you can see we've got something that emulates a realistic look and feel in a webpage that you might be developing. Okay, so now we want to add some authentication logic. Let's go back into our master page, go up to the div that we've reserved— and notice that this div ID is login— and I have a style sheet here which has a collection of styles, and I've defined one for div name login, so you can see it just has basically the same as the clock background— which is the one on the right-hand side— so nothing really fancy about this—this is just some style-sheet usage just so that we get the same look and feel. So I wanted to be able to declare 2 divs that look the same but would contain different content— one set of content being the actual login logic. So here I'm going to get rid of my space holder there, and the first thing that we're going to do is we're going to go over into our Visual Studio Toolbox, go down to our Login Controls tool tab, and grab a Login View control and pop that into the div that we want to contain the login information. So here—Login View—I'm going to change the name from Login 1 to Master Login View because it's contained in the master page, so it's going to be used everywhere, and then inside here I'm going to create a logged-in template and an anonymous template— we'll worry about the role group's template in a subsequent video— And space those just a little bit. Now, let's start with the anonymous template. In the anonymous template here we're just going to say, "Welcome Guest," because we don't know who the user is, but if the user is authenticated, then we do know who they are, so we'll say, "Welcome," and just so these look the same, let's add a semicolon down here too— colon I should say—and here we're going to add a Login Name Control, so let's grab an instance of Login Name, call it Master Login Name, and then the last thing that I want to do—down here underneath— still inside the div, but underneath the Login View Control— I'm going to add a Login Status Control, so the first thing I'm going to do is a little bit of formatting— and you'll see when we run this why— just to make this as realistic as code that you'd write in your production application until we get to the actual authentication mechanism, and then we're going to fake it for this just to show how you can manually write the code to do it yourself, and then in the subsequent video we'll look using the built-in membership provider for ASP.NET. So here we're going to go ahead and grab— again—in our tool box in our Login Controls tool tab, we're going to grab a Login Status control, put that right inline there, and instead of Login Status 1, we'll call it Master Login Status to keep with the way that we've been naming things here. Now after the login status, I'm going to add—again—a space, I'm going to add a right square bracket, and then a couple of more spaces— and you'll see why I've done that just for formatting momentarily here. Now, a couple of more things that we need to do here in our login status control: The first thing that we want to do is specify a Logout Action, and the action that we want to use is Redirect, so basically we're saying when the user logs out, we want to redirect them to someplace else, and we're going to want a Logout Page URL— this is where the user will be directed when they log out, and in our case, we're going to send them to a page that we haven't defined yet, so we're going to call it "LoggedOut.ASPX," and we haven't created LoggedOut.ASPX yet, but that's okay—we'll do it momentarily. Notice IntelliSense is going to tell us that this file's not found yet, but that's okay. Let's go ahead and look in Design Mode here, and now you can see that we've got this "Welcome Guest" here, and then in brackets we have an option to log in. All right, so let's just run that really quickly and see what we have. All right, so notice it tells us we're logged in—and we'll get to that in a moment here— we've got some formatting problems, so let's go ahead and change that a little bit. Let's go back into Source Code view, and the problem is going to be because we don't have enough room, so let's change column span for the login section to be 2 columns and the clock section to be 1 column. And if that doesn't make sense to you, it doesn't have anything to do with the program we're actually building, it's just messing with the formatting here to get things to look right. So now you can see we've got the "Welcome," and notice here I'm pre-authenticated, and I have this log-out option. The reason I'm pre-authenticated—so this is my machine name, and this is my user name on this machine— and the reason you're seeing this automatically is that by default a new ASP.NET application is created with a web.config file that specifies to use windows-based authentication. So if we look in the web.config, and we go down and find the authentication mode section, we can see that by default it's set to windows, and we're going to change it to forms-based authentication. Let's save that, then go run our page again, and you'll note now that we'll be an unauthenticated user, right? So it says, "Welcome Guest, go ahead and log in." Now if I click on this now it will give us an error because we haven't created a log-in page, so let's go ahead and create log-in and log-out pages. So we're going to create a web form, and we're going to use a master page— the one that we were just looking at. Actually, we'll call that "LogIn," and we'll select the one master page we have in our project. We'll modify this momentarily, but while we're creating files, let's just create another one that we call "LoggedOut"— LoggedOut.ASPX. Use the same master page. Now, the logged out page is going to be really simple, so we'll go ahead and get rid of the first content place holder because we're not going to add any custom header content. Here in the second content placeholder— actually this context element—let's say "Main Content," and then here let's just—it's just going to be some text. Remember the LoggedOut.ASPX page is where the user gets redirected to after they log out, so we'll just give it a header of "Logged Out," and then here we'll add a paragraph where we'll say, "You have been logged out; to log back in, please return to the—" and here we'll give them a little help by adding an ahref back to the original logged in page, and we'll select LogIn.ASPX, and we'll tell them if they want to go back to the Login Page— So you can see here, they'll just get this message: "Logged Out; You've been logged out—to log back in, please return to the Login Page," and Login Page is a link. Now, save that, and let's go to the Login Page. Now here in the Login Page— this is where we're going to programatically process the log in, so for us, first thing we're going to do is we're going to break out a little content here. So let's get rid of—again, we're not going to use the content place holder for the header— we're going to use the main content placeholder, so let's go ahead and specify the ID that is in keeping with our standards, and then here let's put a header that tells the user what they're doing here, "Please Log In," and now we'll create some paragraphs. So the first one is going to be where they're going to enter the username, so let's add user name, and then I'm going to insert a text box, so we'll grab a text box out of the tool box, and we're just going to call this "UserName." We're going to need another one of these for password, so let's just use the magic of cut and paste. I'm just adding a space there so that our user interface will line up a little better, and the ID is Password, and since this is going to be a password, let's set the text mode of the box equal to— TextMode=Password—so that the actual text entry will be obscured. Then we're going to need a button for logging in, so let's create a paragraph here and then insert a button. We'll call this "LogIn Button," and make the text "Log In." Now, that's all we need to actually process the authentication, but we want to provide some feedback to the user if what they enter for credentials— if they are unable to authenticate with those credentials, so here let's add an ASP.NET label and give it a more meaningful name— we'll call this "BadCredentials," and let's set the foreground color equal to red, so that's the color of the text that will be displayed. Now the other thing is that we don't want to assume that the credentials are bad before we've tried to use them for authentication, so we'll start with this label with it's visual property set to fault, so this won't be displayed until we try to authenticate with the credentials that are entered, and then if the credentials that are entered are unsuccessful in logging the user in, then we'll display this bad credentials message. So we'll tell them something like, "The credentials that you entered are invalid; please try again." Okay, the only thing left that we have to do is actually process the authentication attempt, so I'm going to double-click on the Log In button to get the code behind— we autogenerate a Click Event Handler for the Log In button— and now we can process the authentication request. Now, I'm going to use some static data. The idea here is that you can programmatically make the authentication decision based on whatever criteria that you want— maybe you're going to write a select statement that selects user name and password from users table where user ID = whatever's in the user ID box and password = whatever's in the password box, or maybe you're going to use some special, custom— some open source LDAP repository— or whatever you want, so in the videos that follow this, I'm going to show you how to specifically use things like the SQL Sever Membership Provider that ships with ASP.NET 2.0, and perhaps I'll do some videos on authenticating against active directory or other authentication stores, but in this case we're just going to do it programatically. The first thing that I'm going to do is create a couple of data structures, and these are going to simulate a repository where username and password get stored, but this could be anything—a database, an xml file, a web service, an active directory instance—whatever you want. So let's create UserNameCollection as— let's make this an array of strings, so as string—and here we're just going to populate this with a collection of usernames— again, just simulating and illustrating that really these usernames and passwords could be stored anywhere that you want. Let's give me an account, let's give the Goo an account— Scott Goo, the godfather of ASP.NET— and let's give Simon Moo an account— Simon Moosio is the guy who drives devdiv communities across the world— while we're doing this, we've got now a collection of usernames, but we'll need the associated passwords. Now normally we'll probably have to populate this collection from whatever our repository is, or we wouldn't populate the collection at all, we would just query against whatever the store was that was holding them, so I'll call it "Password Collection," and we'll just make the passwords "password." So just for the purposes of demonstration there. Now I can say, "For some variable as integer = 02—" however many are in the username collection, so we'll say, "Username Collection - 1" for 0 offset array, and then here we're going to find out whether or not we have a match for username and password, so let's say, "DIM UserName is Valid—" our variable name—"as Boolean," and we're going to find out if it's valid by saying, "String.Compare UserName Text—" so whatever the user entered in the text box for the username with the username and password's current iterance, so here we'll use the Iterator, and the last thing we need to do is tell the compare method of the string class whether or not we want to ignore case, and in the case of the username, we'll go ahead and say we don't care if they enter the username with the exact case that is appropriate. Okay, so I've done that. Now we can create another one that is going to be password is valid since we don't have a successful authentication unless both are valid, and let's grab the text property of the password text entry box in our form, and then of course we're going to look at the passwords collection— the same iterance in the array. However, in this case we're going to set IgnoreCase = fault, so we don't care if the username is the exact case it was stored with, but the password has to be an exact match. So what will happen here is the username will be valid if the one that's entered is the same as the one that we're currently looking at in the array of strings for username, and we don't care if the case is the same. Then we'll do the same thing for password in the passwords collection, but we are going to make sure that the case is exactly the same. Once we've done that— and notice this isn't a foreloop— so we're going to make this comparison once for each iteration through the foreloop. Then we can say, "If UserNameIsValid AndAlso PasswordIsValid," then we have a successful authentication, so we can say, "FormsAuthentication.RedirectFromLogInPage," so we're on the Login Page, but if they're successfully authenticated, we're going to process redirect from Login Page, passing the username—whatever the text is in the username— and we also need to specify whether or not to create a persistent cookie. We're going to cover persistence and sort of remember-me functionality in a subsequent video, so in this case we're just going to say don't create a persistent cookie for now. A persistent cookie is something that will let a user's authentication survive browser sessions, so they can close the browser, reopen the browser an hour later, and still be authenticated as long as the period of authentication that you defined hasn't expired. As I mentioned, we'll cover that in a subsequent video. So let's save all of these, go back to our master page here, and run—so here you can see the page format that we'd expect. I click on Log In, and we go to the Login Page, and I'm going to enter my credentials and my password there, and now I'm going to click "Log In," and notice now the logged in name appears here, and it's just Joe Staggner—the user ID that I used to authenticate— showing the same content—and now if we click Log Out, we get the message "You've been logged out; to log back in please return to the Login Page." I can click on that and go directly back to the Login Page, re-enter my credentials, and now I'm re-authenticated. So that's it—that's how easy it is to use forms-based authentication and the programmatic logic—in this case, manually processing the authentication. In future videos, I'll show you how to use different membership repositories like the SQL Membership Provider so that you don't have to make the decision as to whether or not the user should be authenticated in your own code. [Microsoft ASP.NET] []

Video Details

Duration: 23 minutes and 23 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 6
Posted by: neudesicasp on Sep 20, 2013

Joe Stagner walks through the process to utilize basic forms based authentication programmatically with ASP.NET. It is suggested that viewers read this before viewing. For more information this demo relates to the tutorial located here.

Caption and Translate

    Sign In/Register for Dotsub to translate this video.