The ASP.NET Core 1.0 release is a fundamental release for the ASP.NET ecosystem, and the ASP.NET infrastructure and tooling. Not only because it’s a complete rewrite of the actual web framework, to the extent of an actual reset in the naming to 1.0 and a change to the name, Core; so it’s no longer ASP.NET 5.0, it’s going to be ASP.NET Core 1.0. But aside from that, it’s a fundamental shift beyond the framework for the actual Microsoft organization, and for the entire ASP.NET ecosystem. And a big part of this is because the ASP.NET Framework is now an open-source framework.
Unlike previous versions of the framework, it’s always been free if you’re running on a Microsoft Server, for example. There have been side projects, like Mono, for example, but certainly not the level of traction from Microsoft, in terms of making this a cross-platform framework. And we’re seeing a lot of that change in the ASP.NET Core 1.0 timeframe. The actual framework itself is now open-source and this means a number of things.
For certain people, it’s a good thing. For certain people, it may be a bad thing. Perhaps your company has restrictions on the use of open-source software, for example. But it certainly means far more exposure to the underpinnings of what ASP.NET is, how it works, how it’s constructed, and the ability to drive the direction of, and even contribute to, the ASP.NET project
Table of Contents
- Working with Windows Authentication
- Setting Up Forms Authentication User Login
- Setting Up Forms Authentication User Registration
- Testing Forms Authentication using Simple Membership
- Configure ASP.NET Identity
- Using Cookies to Manage User Sessions
- Configuring a SQL Membership Provider
- Setting Up a SQL Membership Provider Model
- Implement ASP.NET Core Identity
- Authentication Using Azure Active Directory
- Azure Active Directory B2C
- Azure Active Directory B2B
- Identity Management Using Session Cookies
- Acquiring Access Tokens with MSAL
- Working with Custom UserStores Using Middleware
- Testing a SQL Membership Provider
- Create Custom Membership Providers
Working with Windows Authentication

In this demonstration, we’ll look at configuring Windows Authentication within an MVC application. Let’s start by creating the application. We go to the File Menu, choose New, and Project. I’m going to select an ASP.NET Web Application, and then down below here, give the application a name. I’m going to call it Course14_WindowsAuthentication. Down below that, I’m going to give the solution the same name, but with the word Solution at the end, and then I’m going to hit OK.
Next, it wants to know what type of ASP.NET application we want to create. Here I do want to make it an MVC application, but what I want to show you is over to the right, we do have a Change Authentication option. Notice that authentication is set to No Authentication currently, so if I wanted to, I could click the Change Authentication and I can go with Individual User Accounts, which is using users from a SQL database. We could go and specify that we want accounts from Work or School, which is authenticating against another directory service like Active Directory, or Azure Active Directory, or Office 365. Or I could go with Windows Authentication. So, my point here is, is that if you’re developing your MVC apps and you know you want to use Windows Authentication, they kind of have a quick option to enable it for us during the creation process of the application. I’m not going to change this here, I want to hit Cancel, I’m going to leave it set at No Authentication.ASP.NET
Keep in mind, if I really was creating an application and I knew I wanted to use Windows Authentication, I’d probably switch it right there and then that way the feature is enabled and ready to roll. In this demonstration, I want to show you how you can enable the feature manually yourself, so I’m not choosing that option. So, I’m going to hit OK. Now that the application is created, over to the right-hand side
Of the screen in our Solution Explorer, I want to go into the Web.config. The Web.config is where all the application configuration settings are. And within here, we can add an authentication setting. So, I’m going to go and add authentication, and I’m going to say the mode of authentication is equal to Windows authentication. So, within your ASP.NET web application, you can configure Windows Authentication very easily by going and configuring the authentication tag. Now other examples here, we could also use forms authentication, where the user is logging in through a webpage.
So, in this demonstration, I don’t really want to do that. I want to use Windows Authentication. Now the other thing that you can do as well is that’s the authentication tag, you can also set up the authorization tag. And with the authorization tag, you can specify users in groups that are allowed or denied access to the web application, right? So, what I’m going to do here is I’m going to say, actually, I’ll go with the deny users, notice that I have roles. I can deny verbs if I wanted to, so things like POST methods and GET methods, that kind of idea.
So, I’m going to deny users=, and you can do stuff like, bob. Now with Windows Authentication, it would take the domain name, backslash, the username kind of syntax. If I’m using forms authentication, then I can use things like just the word bob, whatever the username is, right? So again, I would use whatever the domain name is \bob, and that would deny Bob access to the site.ASP.NET
Now in this example, what I want to do is I want to make sure anonymous access is not allowed, so I do a deny space users=?. And then you could go and add another rule, and these rules are read from top down, so I could allow users if I wanted to, right? So, I just want to make sure that I go and deny anonymous users access to the site, so that I’ll enforce that everybody is authenticated. So, I’m going to save that.
Now, I’ve got two other quick things that I want to do here. First thing is I want to change one of my pages. So, I’m going to go into my View, go to Home and I’m going to go to Index. And I do want to show the username here somewhere on this page. So, I’ll do it at the top, I think, maybe right after this. So, to display the username, you can use the @user dot, and then you can grab the identity of the user. Or if you wanted to, it’s very common to check to see if the user is in a specific role. So maybe I only want to show a hyperlink if they’re in a particular role. So I’m going to do .identity and then .name. So, I can check to see if they’re authenticated. In this case, I just want to display the username right there on the page. So, I’m going to hit Save All, and we’re done configuring the web application.ASP.NET
Now another thing that’s important here is we also have to configure our web server settings. So I am using the development environment, so if I select up top here my project, Course14_WindowsAuthentication. You can see here; we do have some Development Server settings. So this is important because I am using the web server that’s built into Visual Studio, but I do have to configure its settings. In real world, you’d have to make sure that the IIS box that’s hosting the MVC application is also configured properly. And what I mean by configured properly is we want to make sure that Anonymous Access, disable Anonymous Access. I’m going to leave Anonymous Access Enabled, keep in mind my web app has it disabled, but from a server point of view, it is enabled.
And, I do want to set the Windows Authentication, that’s the setting that I’m looking for here. So, I do have to make sure that Windows Authentication is Enabled on the web server itself. So, it’s enabled in the web application, but now the web server has it enabled. So, if I hit Save All, and then I’m going to run my page, and it should show my currently logged on user. So, Windows Authentication is common for Internet applications, where you want to leverage the existing account that the user is already logged in as. So, it should show my computer name and my username, and here it is here, right? I’d probably plan this a little bit better and kind of put it in a better spot, but you can see I am logged in as W8OfficeB\gclarke. So, it’s obtained my Windows username.
Setting Up Forms Authentication User Login

In this demonstration, we will take a look at how to enable forms authentication within your MVC application. Now I want to first start it with a quick little tour of what I’ve configured here in my MVC application. I started with just a basic empty application that starts with the default home controller and I haven’t modified this it’s basically just has the Index method that returns an Index view the About method that returns the an About view and a contact method that returns the Contact view. So it’s kind of the default application, MVC application when you create that application.ASP.NET
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = “Your application description page.”;
return View();
}
public ActionResult Contract()
{
ViewBag.Message = “Your contact page.”;
return View();
}
}
}
code ends. He then closes the HomController.cs tabbed page [Video description ends]
Now what I have added though is in my models I did create a user account model. And the purpose of this model is to represent user account objects that can be used to authenticate against the system. So nothing really fancy here, it’s just your basic class. So it’s a public class user account where I’ve created a user ID property, I’ve created a username property, a password property and also a confirm password property.
[Video description begins] The presenter selects the Models folder in the Solution Explorer and then selects the UserAccount.cs file. The UserAccount.cs tabbed page displayed and he explains the following code displayed in it. Code starts: public class UserAccount
{
[Key]
public int UserID{ get; set; }
[Required(ErrorMessage =”Username is required.”)]
public string UserName { get; set; }
[Required(ErrorMessage = “Password is required.”);
[DataType(DataType.Password)]
public string Password{ get; set; }
[Required(ErrorMessage = “Confirm password is required.”)]
[DataType(DataType.Password)]
[Compare(“Password”,ErrorMessage =”Your confirm password does not match your password.”)]
public string ConfirmPassword { get; set; }
code ends.
Now I did add some validation, a little bit of validation, not a lot here, but I did specify that the UserID would be the primary key. I also specified that, the Username is required and so is the Password, and ErrorMessages for those. I also specified that the Password was of DataType Password, that way we don’t see the password as it’s being typed. And then I have the ConfirmPassword property is used in the Compare annotation to compare it against the Password property to make sure that their equal and if not, an error is displayed. So just a few properties with inside that user account model. Now I also have a AppDBContext and this is basically just the database context for my application that I’ve created here. So I am going with a code first model.ASP.NET
[Video description begins] The presenter closes the UserAccount.cs tabbed page and clicks the AppDBContext.cs file under the Models folder in the Solution Explorer. The AppDBContext.cs tabbed page displays. He explains the following code. Code starts: public class AppDBContext:DbContext { public DbSet<UserAccount> userAccount { get; set; } } } code ends. He the closes this tabbed page. [Video description ends]
So those are my two models that I’ve created. Now the next thing that I have is, I do have a login page that’s created based of my user account model. So you can see that at the top here that the model is pointing to the user account object. So I just have a basic form created here, that displays the labels for the username and the password box. So that’s all set up, ready to go and so that’s our log on screen.ASP.NET
[Video description begins] The presenter selects Views – Account – Login.cshtml in the Solution Explorer. The login.cshtml tabbed page with the following code is displayed: @model Course14_FormsAuthentication.Models.UserAccount
@{ ViewBag.Title =”Login”; }
<h2>Login</h2>
@using (HTML.BeginForm())
{
@Html.AntiForgeryToken()
<div class=”form-horizontal”>
<h4>UserAccount</h4>
<hr />
@Html.ValidationSummary(true, “”, new { @class = “text-danger” } )
<div class=”form-group”>
@Html.LabelFor(model => model.UserName, htmlAttributes: new
{ @class = “control-label col-md-2” } )
<div class=”col-md-10”>
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = “form-control” } } )
@Html.ValidationMessageFor)model => model.UserName, “”, new { @class = “text-danger” } )
</div>
</div>
code ends.
And I also have some forms for the about page, the contact page. And those are the default views that were created when you create the application. So, what I want to do now is I want to go and enable foreign space authentication within this application. And make it so that you have to go to this log on screen and log in to the application before you can access any of the pages. So kind of two major steps to do that. The first step is that you want to make sure that you have some log in logic. So if you take a look at my form here, I’ve got the form all set up ready to go, and sorry the, the controller class is what I wanted to show you. I also have the AccountController class set up and it contains a login method. Now the login method that’s here. I’ve got the login method is for post actions, so it must be for HttpPost request, and I instantiate my database object. ASP.NET
And then I what do is I check to see if the username and password that was utilized if it exists. If it does, it stores the object or the result in record within inside this user. And I checked to see if the user’s not equal to null. If it’s not, I take things like the Username and I store it in the Session variable. And then here’s the key point. With forms-based authentication, something has to track whether you’ve logged in or not. So with ASP.NET MVC, they have a cookie that they use to track whether or not you’ve logged in. So what happens is, the application will check for the existence of that cookie.
[Video description begins] The presenter selects Controllers – AccountController.cs from the Solution Explorer. The AccountController.cs tabbed page displays. He explains the following cod. Code starts: [HttpPost] public ActionResult Login(UserAccount user)
{
using (AppDBContext db = new AppDB Context())
{
var usr = db.userAccount.Single(u => u.UserName ==user)
if (usr != null)
{
Session[“UserID”] = usr.UserID.ToString();
Session[“Username”] = usr.UserName.ToString();
//return RedirectToAction(“LoggedIn”);
FormsAuthentication.RedirectFromLoginPage(Session[“Username”].ToString(), false); }
else
{
ModelState.AddModelError(“”, “Username or password icorrect “)
}
return View();
}
code ends.
Now, what I need to do is if you type the correct username and password, I need to set back cookie. And there’s a couple ways that you can set that cookie. You can call up on the FormsAuthentication dot and then there’s the Authenticate method that we can call upon. If you call upon the Authenticate method, then it sets the cookie. Or you can set the cookie with a RedirectFromLoginPage.
And that’s kind of what I’m using here. And the reason being is, the way I want it set up is that if you try to go to, let’s say, the About page, then you’re going to get sent over to the login page because you haven’t logged in. But then once you log in I want you redirect it to the page that you requested. So that’s why I’m using the RedirectFromLoginPage method. It will redirect him to the page that the user has requested, but also it sets the authentication cookie so that the application knows okay, they’re logged in now. So any other pages that you request you’ll be able to access without getting redirected to the login page.ASP.NET
Now when I called the RedirectFromLoginPage method, by passing the username so that get stored with inside the user object. And I can display that if I wanted to on different pages. And then I also specify whether or not I want a persisting a cookie. And a persisting cookie could be use so that the user launches the browser tomorrow, let say and they don’t have to log in because the cookies persistent it was stored to disk, right? So I’m going with the false here. It’s not a persistent cookie. So if I close the browser and open it again, I’m going to have to login to the application. So that’s FormsAuthentication.RedirectFromLogin. Now just a little note here, FormsAuthentication is only available to me here because up top I went and imported the System.Web.Security name space, which is not imported by default, right? So I had to go and import that. So we’re ready to go.
The only thing next is to enable forms authentication. And you enable form authentication through the web config file, so if I open up the web config file, within there you go to your system.web section of the Web.config file. ASP.NET
Code starts
<system.web>
<compilation debug=”true” targetFramework=”4.5.2” />
<httpRuntime targetFramework=”4.5.2” />
<httpModules>
<add name=”ApplicationInsightsWebTracking” type=”Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web” />
</httpModules>
</system.web>
code ends.
And I’ll go rate here underneath the HTTP modules. And underneath there what you do is you set the authentication tag. And with the authentication we specify our mode attribute and mode= and you can see we do have things like Windows authentication or Forms authentication or Passport authentication. So I’m going to specify that I do want to use Forms authentication, and then I’m going to close this off, hit Enter. And then in between here you specify any settings for Forms authentication.
So for example, I want to specify what the login URL is, so I do a forms, setting and then I’m going to do a defaultUrl=, and I’m going to specify the path to the default page, or in this case, the default action. So I’m going to go to the Home controller. There’s an Index action that I’m in going to redirect them to. So that’s a default after they logged in.
Now keep in mind, that’s what would be used if I wasn’t using my redirect from log in method. And then I’m going to specify the log in URL, which is really the critical attribute here that I want to set. The loginURL= and then I’m going to point to the Account controller Login method. So there is our authentication being set. So very easy to set it also notice the Intellisense was available so I didn’t have to memorize each of the different attributes in that. ASP.NET
Code starts:
<authorization>
<deny users=”?”/>
<allow users=”*”/>
</authorization>
code ends. He explains that the ? is for anonymous users and * is for all other users. The Web.config tabbed page is open. The presenter types the following after <httpModules> . Code starts:
<authentication mode=”Forms”>
<forms default Url=”~/Home/Index” loginUrl=”~/Account/Login” />
</authentication>
code ends.
So just to kind of recap, the mode here of authentication is Forms based authentication, which means you’re going to login through a webpage. The actual login webpage that you’re going to use is specified here through the loginUrl. So what’s going to happen a request is going to go up to the AccountController.Login method, which it will return the view of the login view. And then once you are logged in, the default page, if you haven’t requested one, will be the index. Now the other thing that you want to set here is our authorization setting. And with authorization, we want to allow and deny user. So one of the things that we are got to do, is we are got to make sure that we deny anonymous users.
So we deny users=”?” is how we specify anonymous. Now these rules are read from top down so it’s important that I make sure is deny the user I don’t want, which in this case is the anonymous and then I’m going to allow all other users. So allow users = * how you can allow other users. If I didn’t want to allow all users, I could just go and specify a user account if I wanted to. So I can say okay, I want to allow GlenEClarke and BobSmith. So I can do that if I wanted to. But I’m just going to say all users are allowed. So I’m going to hit the Save button up top here. Now just to test this out really quickly to see if our authentication is working, is I’m going to request the About view. So I’m going to right-click on the about view here and I’m going to view that in a browser. Now if forms authentication is working for me, what’s going to happen is, I haven’t logged in so I’m not allowed to see that page. Anonymous people aren’t allowed to see the page so it should redirect me right away to the log in page so I shouldn’t see this about page.ASP.NET
So if you let the browser, it launches my browser. You can see up top it’s headed towards the About. But notice I do get redirected to the login page. And also notice that the return URL is there as well. So it is tracking the original page that I had requested, right? And then I could go and I could log in. Notice that it sent me to the About page, right? Which is the original page that I requested.
Setting Up Forms Authentication User Registration

During this video, you will learn how to set up forms authentication user registration functionality using a Simple membership provider in an ASP.NET MVC web application in Visual Studio 2017.
In this demonstration, we’ll take a look at how to implement registration functionality within your MVC application. You can see here, over on the right, that I have a number of elements already created within my app. First thing I want to point out is I do have a couple models created. So I do have the user account model that I’m using for the definition of user account objects. So storing user names and passwords, that kind of idea.
Code starts:
{
public class UserAccount
{
[Key] public int UserID { get; set;
}
[Required(ErrorMessage =”Username is required.”)] public string UserName { get; set; } [Required(ErrorMessage = “Password is required.”)] [DataType(DataType.Password)] public string Password { get; set;
}
[Required(ErrorMessage = “Confirm password is required.”)]
code ends
[Video description ends]
So you can see here, we’ve got the user account class, we’ve got the UserID, the UserName, the Password, the ConfirmPassword. And I also have some validations set up.
[Video description begins] The presenter further scrolls down the window. The following code is displayed.
Code starts:
[DataType(DataType.Password)]
[Compare(“Password”,ErrorMessage =”Your confirm password does not match your password.”)]
public string ConfirmPassword { get; set; }
}
Code ends.
So flagging elements as being required, and comparing the ConfirmPassword against the Password, that kind of idea. I also have the AppDbContext class or model over here. It basically sets up my database context for storing user account objects. And I’m following a code first kind of mentality here.
Code starts:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Course14_FormsAuthentication.Models
{
public class AppDBContext:DbContext
{
public DbSet<UserAccount> userAccount { get; set; }
}
} Code ends.. He then closes the file. [Video description ends]
Then we’ve got our controllers. So I have an account controller that I created that will handle all user account activity, such as user accounts logging in or registering user accounts.
The presenter clicks on c# AccountController.cs under Controllers folder. AccountController.cs is open in the editor, The following code is displayed. Code starts: using System.Web.Linq; using System.Web.Mvc; using Course14_FormsAuthentication.Models; using System.Web.Security; //must import for FormsAuthentication namespace Course14_FormsAuthentication.Controllers { public class AccountController : Controller { // GET: Account public Action Result Index() Code ends.
So if I take a look at this controller, the first thing you’ll notice is that I am importing my models right at the top. And I also import System.Web.Security. Now down below that, let’s go right to the registration.
The presenter scrolls down the window the following code is displayed:
Code starts:
public ActionResult register()
{
return View();
} [HttpPost] public ActionResult Register(UserAccount account)
{
if (ModelState.IsValid)
{ using (AppDBContext db = new AppDBContext())
{
db.userAccount.Add(account);
Code ends
So I’ve got two methods created for registration. So I’ve got the public ActionResult Register method where all it does is return the view. And I’ll show you the view here in a minute. The view is the webpage that is used for registering the user account.
Now, I want you to notice that this first Register method is basically going to handle get request. So when somebody sends a request to the Register method, this will return the view. Which is an empty view where they fill in the information to register the user.ASP.NET
Once they fill the information in and they hit the create button or register button or submit button whatever you set up on that view, then that submits up to the Register view again, but, or sorry, the Register Method. But this time we want to make sure that we have a method specifically designed to handle post request for registration actions. So, I make sure I use the annotation here HttpPost.
Code starts:
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.UserName = “ created successfully
}
return View();
He then points to the code of post request for registration actions.
And this is where we implement the logic to register the account. Now, you’ll notice that this Register method does have a parameter set up of the UserAccount type, and I call it account. First thing I do is I check to make sure that the model is valid, right, or the model state is valid. So when they fill in the properties, we want to make sure that everything passes its checks like whether or not items are required. And in my case, I make sure that the confirm password matches the password, right? So we want to check for that first before we try to even create or register the user. Then I obtain a database context. So I create the database variable. And this database variable’s going to be used to actually add and delete information. So then we do a db.userAccount.Add and I want to add that account to the database. Now keep in mind, that account isn’t permanently stored in the database unless you call the database.SaveChanges. So if you want that change to persist, then you’re going to have to call the SaveChanges method. So I save the changes, then I go and clear out the model state. And then I go and set my ViewBag.Message to the user account was created successfully, right, so whatever the username was. And that’s just so that when I go back to the view, so I return the view, it’ll display that information at the top of the page. Because I’m displaying the ViewBag within the view. ASP.NET
Code starts:
} return View();
}
Code ends.
So that’s the first thing that you have to do, is set up the Register methods, then you’re ready to create the view. Now, I’ve already created the view, and I’ll show you the code, but I just want to show you how I created the view. You can create the view just by right clicking on your Action Method, and then choose the Add View. Here, they want to know what you want to name the view.
He highlights Register, right-clicks, and selects Add View from the menu. The Add View dialog box displays. There is a View name field, populated with Register, a Template drop-down field, set to Empty (without model), an inactive drop-down field Model class, an inactive drop-down field Data context class. In an Options section, there is an unchecked check box, Create as a partial view, an inactive checkbox, Reference script libraries, and a checked check box, Use a layout page, which has a text field with a Browse button beside it and an instruction beneath, (Leave empty if it is set in a Razor _viewstart file). There are Add and Cancel buttons.
I’ve already got a registered view, so let me just call this Register2. And they want to know if you want to use a template. Now, I did go with a template. So you could say, do you want to create the view for creating objects, which is what I did. Or do you want to go with editing objects or deleting viewing details, that kind of concept. So, I did go with the create, and then I specified the class was for the user account object. That’s how this template knows which text boxes to include on the form. So it’s going to need a text box for things like the username and the password, and confirm password. And then they want to know the database context as well. So there’s my model class that I created for the database context called AppDbContext, right? And I just hit the Add button, and it created the view.
The presenter types View name as Register2 and selects Create in the Template drop-down. The Model class and Data context class fields become active, the Data context class automatically set to AppDBContext (Course14_FormsAuthentication.Models). The Reference script libraries checkbox becomes active.
The presenter selects UserAccount (Course14_FormsAuthentication.Models) in the Model class drop-down. He then clicks the Cancel button.
And the view, take a look at the view. So here’s my register view, in the register view, so it generated all this code. I just went and deleted any kind of fields that I didn’t want, right? But you can see at the top of the view, here’s our ValidationSummary. So do we show a validation summary of all the errors, if there are errors?
There is our ViewBag being displayed here. So again, once I create a register user, when we come back to this page, the ViewBag message will display at the top. And then you can see here we’ve got a label for the Username. We’ve got an edit box for the Username, and the validation message for the Username. And then we do the same thing for the Password and the ConfirmPassword. So there’s a label for ConfirmPassword, there’s an edit box for ConfirmPassword, and there is a validation message for ConfirmPassword as well. Then down below, we have a Submit button and the value there is Create. Maybe what I’ll do is I’ll change this to Register.
Testing Forms Authentication using Simple Membership

In this demonstration we’ll take a look at testing out our form’s authentication. Before I run the application, the first thing that I want to do is just review my Web.config file, which is where all our application configuration settings are stored. Now you’ll notice within the Web.config file that we do have, within inside the system.web section, we do have an authentication tag. And that authentication tag has been configured for Forms authentication.
Code starts:
<add key=”add key=”UnabtrusiveJajaScriptEnabled” value=”true >
</appSettings>
<system.web>
<compilation debug=”true” targetFramework=”4.5.2” />
<httpRuntime targetFramework=”4.5.2” />
<httpModules>
<add name=””ApplicationInsightsWebTracking” type=”Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web” />
</httpModules>
<authentication mode=”Forms”>
<forms default Url=”~/Home/Index” loginUrl=”~/Account/Login” />
</authentication>
<authorization>
<deny users=”?”/>
<allow users=”*”/>
</authorization>
</system.web>
Code ends.
Now with Forms authentication, we want to specify the login Url. And here we’re specifying that we want to send any request for a user that hasn’t logged on.
login Url = quotation mark ~/Account/Login”
We want to send that request to the Account controller, the Login action. Now we also want to make sure that everybody has logged on to the application. So we also configured in the authorization section, we add the entry to deny users=?, which means to deny anonymous users. Whereas after that we have allowed all other users. So what happens is the authorization section is read from top down. So it makes sure that it denies an anonymous user. So if you haven’t logged in, you’ll get redirected to the login page at that point, right?
Code starts: <authorization>
<deny users=”?”/>
<allow users=”*”/>
</authorization>
And all other users authenticated would be allowed. So to test this, what I’m going to do is I’m going to send a request for the contact page. Now what should happen here is that because I haven’t logged in, the application should redirect me over to the login page so that I have to log in before I can see the contact page. So I right-click on the contact page and I choose to View that in a Browser.
And notice that I’m not seeing the contact page right away, I’m redirected to the Login. So now I’m going to log in with my UserName and Password. And you can see that it has redirected me to the Contact page after getting logged in.
So in this demonstration, we tested out our forms authentication.
Configure ASP.NET Identity

In this demonstration, we’ll take a look at how to configure ASP.NET Identity within your MVC application. To get started, what we’re going to do is to create a brand new application.
So we’ll go to the file menu, choose New, and Project. And we are going to create a new ASP.NET web application. And here, I’m going to call it, Course14_Identity. And, I will create a different name for the solution files. We’ll just put the word Solution on the end. And, then I choose OK.
The New Project window is displayed. The presenter selects the ASP.NET Web Application (.NET Framework) template and types the application Name as Course14_Identity. He types Solution name as Course14_IdentitySolution and clicks OK. The New ASP.NET Web Application – Course14_Identity window is displayed. The MVC template is selected by default.
Now here we can see the different types of ASP.NET applications that you can create. So you can go and create the classic web forms if you wanted to a web API application. Now obviously in this case where we want to do is we want to create an MVC application. When we create the MVC application, you can specify kind of what convention you want to follow. Whether you want to follow web forms or web API.
In our case, we do want to reference MVC and use MVC folder structure. We’re not going to add a unit test here. But one thing that we are going to change is that over on the right hand side, you can see the authentication type that we’re going to be using for this application. So by default, the authentication type is set to no authentication. So the application is just going to be used by anonymous users. Nobody has to log in to access the application. Now, we do want to change this. So, we’re going to hit the Change Authentication button.
And over on the left here, you can see that the, again, the default is No Authentication. So, we don’t require anybody to log on to access the application. Whereas what we can do is we can specify that we do want to use authentication. So we’re going to enable authentication. And we do want to enable authentication for Individual User Accounts.
Now you would use this option, over here on the right, they show you if you want to use this for application to store user profiles in a SQL database. Also, users can register and sign in using existing accounts from Facebook, Twitter, Google, Microsoft, or any other number of different authentication providers. So this kind of the option that we want to use for authentication.
Just before I choose that and hit OK, notice that as well, that we do have work or school accounts as an option. So what’s great is this is used to authenticate against your existing active directory environment or your Azure active directory environment. Or maybe even Office 365. So you can choose your option here as far as what type of workers school account that you want to go with. So notice that I can go with the Cloud- Single Organization, and you specify your cloud domain name here.
Also, you can go with an On-Premises environment as well. And then you specify the URL to the On-Premises environment in the app ID. We could also configure Windows Authentication, which is just used for internal applications on your network itself.
And it’s just going to use your active directory credentials or your Windows credentials. Now again, in our case for identity authentication,
we do want to go with individual user account. And then I’m going to choose OK. So notice that it has changed the setting and it’s going to go with individual user account. So hit OK. And it’s going to create the application.
Now one of the things that’s great about creating these MVC applications today with these templates, is they have all the core functionality already implemented and written for you. So there’s a bunch of templated code that’s going to exist that handles the authentication services. Now the cool thing is that you can customize that code if you wanted to. So I just wanted to give you a tour here of the identity functionality with inside the application.
First thing I’m going to do, is I’m going to run the application. So what I’m going to do here is go to my Views. And let’s just say I want to go to the Home View, and I’ll go to the Index page. I’m just going to view the Index page, that’ll send a request to the application, and it’ll display that view. Now, in this case, what I just wanted to show you is that when I run the application.
This is what it looks like by default. Notice that up top here, in the right-hand corner, we do have a register and we do have a log in link.
The Home Page displays in the browser. The Home page contains a task bar with options: Application name, Home, About, Contact, Register and Log in.
So they do have the functionality for identity authentication built automatically. Now I’m going to go with the register here. So, I’ll click the register link. And I’m going to register with my Email address, so gleneclarke@hotmail.com. My Password, just use my typical course password. And then I’m going to hit the Register link.
So I want you to notice that the Register functionality is already incorporated into the application. Notice that I have logged in. It shows up top here Hello gleneclarke@hotmail.com! I can Log off if I want to, right? We’re going to log off there. One of the things that I wanted to show you is that if you’re going to use the identity provider, one of the cool things is that you can create the application and then turn around and run the application.
Now if you’re not on the Server Explorer, you’re probably on the toolbox by default. So I go to my Server Explorer, I can expand to my database connections. And I expand out the database connections database. Let’s just take a look at the tables here. If you’ve used membership services in ASP.net in the past, you know that there is a number of tables that they use to store Authentication information. And with identity authentication, it’s very similar. Right? They do have a number of tables here.
The tables are a little bit different, but it’s basically the same idea. So you can see they do have an ASP Net users, they do have an ASP user logins, user claims, roles as well. Right? So groups that users are a member of. So they have the whole system already set up and templated for you. Again, in my case, all I had to do was run it. And the first time you run it, as soon as you register, it creates this default database. Now, I just wanted to show you the ASP.NET users table. If I expand that out, notice it’s got the email address, the email confirmed, the password hash. That’s what I want to show you, is that. With this templated solution, they follow best practices. And with these best practices is things like, all right, we’ve got your user registered.
There’s the email address for that user, right? Which happens to be my login name as well. But notice that the password is not stored in plain text, right? So the password is hashed. Which is kind of nice. They also have other characteristics like the phone number, this is awesome. They also have the capabilities with identity authentication, is that we can implement two factor authentication where a text message is sent to the phone in order to authenticate. So it’s not enough just to know using new password, you also have to have that phone in your hand. So all kinds of cool things like that.
The last thing that I wanted to show you here is that, so that’s all ready to go. The last thing I wanted to show you is, if I go to my controllers. Just wanted to show you that a lot of the code is already set up, raring to go. So if I go to my account controller here, you’ll notice that they’ve got all of the code for log on functionality creating users, that kind of idea. Now within this account controller, notice that they’re calling upon classes called userManager and signInManager.
Code starts:
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public Accountcontroller()
{
}
public AccountController(ApplicationUserManager userManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
Code ends.
So these classes here are classes that have all the functionality for managing user accounts and managing the whole sign in process, right? So you’ll notice that the account controller is working with userManager objects and signInManager objects, right? Now if I show you those up top here, we’ve got a list of all of our classes within the application. So look at all the classes that they have all built here. So I want to go to the, let’s go with the user manager. So I’ll go to the user manager class, and then just at the top here if I scroll down through, you’ll notice that they’ve got all the kinds of methods set up for handling user account management. So let me just find an example here. So here’s an account log in.
Code starts:
//GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult>
Code ends. [Video description ends]
Notice that they have it set up. There’s your get request and your post request methods, so that different code is executing depending on what the purpose is. Here’s a great little example. So here they’re checking the status of the sign in.
Code starts:
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View(“Lockout”);
Code ends.
So if it was a success, they return them to the URL that was requested. If the status is the accounts locked out, then they return them to a view, the lockout view, right? So we have different pages that are being returned. And again, this code is here so that you can customize it. So that’s kind of the great thing about the identity authentication within the inside of our applications. So in this demonstration, we saw how to configure identity authentication within an MVC application.
Using Cookies to Manage User Sessions

In this demonstration, we’ll take a look at how to store information in a cookie within an MVC application.
Now I’ve already created the code, let’s review our code. On the account controller, I chose to use the login process, right? So I do have my login action here, which is executed when somebody tries to log in. I obtain the database connection or the database context to check to see if the username and password is correct. And if it is, I do create a couple session variables. But in this example, what we want to do is see how to store information inside of a cookie.
Code starts: //get method public ActionResult Login ()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (AppDBContext db = new AppDBContext())
{
var usr =db.userAccount.Single(u => u.UserName == user.UserName if (usr != null)
{
Code ends.
Code starts:
[“UserID”] = usr.UserID.ToString();
Session[“Username”] = usr.UserName.ToString();
// return RedirectToAction(“LoggedIn”);
//Store preference in a cookie HttpCookie myCookie = new HttpCookie(“SportCookie”);
myCookie.Value = “Hockey”;
myCookie.Expires = DateTime.Now.AddDays(2);
Response.Cookies.Add(myCookie);
Code ends.
So to store information inside of a cookie within MVC, the first thing that you want to do is create a cookie object. And the cookie object is of the HttpCookie type itself. So I do an HttpCookie, the cookie that I’m going to create is going to be called myCookie, that’s the name of the object equals a new HttpCookie. And I give the cookie a name, it’s a SportCookie. So I want to store the user’s favorite sport inside of a cookie so that I can retrieve that from different pages. Now once you’ve instantiated a cookie object, then you specify the Cookie.Value. So in my case myCookie.Value = and the word Hockey is going to be stored in the cookie. Now if you wanted to, you could create what we call a persistent cookie, which means that by default these are session-based cookies. So if the user closes down the browser, the cookie value is lost. But what you could do is store it persistent, which means that it writes it to disk.
In order to write it to disk you have to give it an expiration property. A future date. So in this case I do a myCookie.Expires equals, and I add the two days to the current date. So it’ll store the expiration date in a cookie file and that’ll expire automatically in two days. Now what this does is this means that if we launch the browser automatically, it’ll retrieve that information from file. Which is kind of cool. Now, after you set the value and the expires property, then what you have to do is you have to write that information back to the client.
So, keep in mind, I’m in server-side code here, so all this stuff is happening on server. So I have to call upon the response object .Cookies.Add. So I have to add that cookie to the cookies collection. So it writes it back to the client in the response message. So that’s how we create a cookie. Now what I need to do is I need to read that cookie data. And you read the cookie data, again, we’re in server side code. We’re going to read the information from the request message. So the browsers automatically submit cookie data if they have any within the request message itself.
Code starts: @{
ViewBag.Title = “Contact”;
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<div>
@{
HttpCookie myCookie = Request.Cookies[“SportCookie”];
}
Your favorite sport: @myCookie.Value
</div>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
Code ends.
So to retrieve the information, what I’m going to do is I go into my contact page here, which is where I have my contact details displayed. And what I’m going to do is I’m just going to go and print the information on this contact page, for no particular reason. Let me just add in a space here just to separate it a little bit.
Now in order for you to retrieve the cookie data, again, remember that the cookie data is submitted by the client up to the server in the request message. So what I need to do is I need to create an HttpCookie variable again. So in this case I’m going to call it myCookie and it equals Request.Cookies and I’m going to retrieve SportCookie from the request message. That’s going to get stored into this variable and all I got to do is retrieve the value of the variable. So here in my razor code, I’m doing @myCookie.Value. So it’ll make a little sentence out of it. Your favorite sport is and retrieves the value of the cookie. So let’s test this out. I’m going to hit Save All here and I’m going to send a request for the contact page. Now keep in mind, because I have forms authentication set up, I will have to log in.
But once logged in, it should redirect me to our contact page. And you’ll notice that it was able to retrieve the cookie value called hockey.
Configuring a SQL Membership Provider

Code starts:
Line 17<system.web>
Line 19 <compilation debug=”true” targetFramework”4.6.1” />
Line 20 <httpRuntime targetFramework”4.6.1” />
Line 21 <httpModules>
Line 22 <add name=”ApplicationlnsightsWebTracking” type=”Microsoft.Applicationlnsights.Web.ApplicationlnsightsHttpModule,
Line 23 </httpModules>
Line 24 <pages validateRequest=”false” />
Line 25 </system.web>
code ends.
We are going to use an existing application called My HR. We’ll take a look at the web.config file, and we’ll make changes to it. So on line 18, type authentication mode = “Forms”. On line 19, type forms loginurl=”~/Account/Login” timeout=”2800″ and then type the closing bracket. On line 21, type membership type defaultProvider=”MyMembershipProvider”. Type providers, type clear. Type add, type name, and type MyMembershipProvider. Type type=”MyHr.Lib.CustomMembershipProvider”.
Code starts:
Line 18 <authentication mode=”Forms” >
Line 19 <forms loginUrl= “~/Account/Login” timeout”2800” />
Line 20 </authentication>
Line 21 <membership defaultProvider=”MyMembershipProvider”>
Line 22 <providers>
Line 23 <clear/>
Line 24 <add name =”MyMembershipProvider” type=”MyHr.Lib.CustomMembershipProvider”/>
Line 25 </providers>
Line 26 </membership>
code ends. [Video description ends]
I’m going to look at the AccountController now. I’m going to add code for creating users. So on line 39, type membership.CreateUser
[Video description begins] The presenter switches to AccountController.cs tab. He scrolls to a section of code: Code starts:
Line 24 [HttpPost]
Line 25 public ActionResult Create(string Username, string Password)
Line 26 {
Line 27 string message = “”; MembershipCreateStatus status;
Line 30 try
Line 31 {
Line 32 if (Username == null || Password == null || Username.Length < 1 || Password.Length < 1)
Line 33 {
Line 34 message = “Invalid Username/Password!”;
Line 35 }
Line 36 else
Line 37 {
Line 38 //Create the account
Line 41 message = “Account created for “ + Username + “ !”;
Line 43 }
Line 44 }
Line 45 catch (Exception ex)
Line 46 {
Line 47 message = ex.Message;
Line 48 }
code ends. [Video description ends]
(Username, Password, ””, ””, “”, true,out status);.
[Video description begins] The presenter types the following code line:
Line 39 Membership.CreateUser(Username, Password, “”, “”, “”, true, out status);
Code starts:
Line 82 //Login
Line 83 var login = true;
Line 85 if (login)
Line 86 {
Line 87 //Authenticate the user
Line 88 FormsAuthentication.SetAuthCookie(Username, false);
Line 90 message = “Login Successful!”
Line 91 }
code ends.
Setting Up a SQL Membership Provider Model

To start, I’m going to add new database tables to the database. So under App_Data, I’m going to click on MyHR. I’ll click on the server explorer thumbtack,
I’ll look at the tables that we have currently. So currently, there is a comment table that contains our comments. So I’m going to add a new table called Users, right-click on Tables,
Code starts:
Line 1 CREATE TABLE [dbo].[Table]
Line 2 (
Line 3 [Id] INT NOT NULL PRIMARY KEY
Line 4 )
code ends.
On line 4, type username nvarchar(255) not null, password nvarchar(255) not null, salt nvarchar(255) not null. In the upper left hand corner, click Update, and then click Update Database. I’m going to refresh the database table, so right-click on Tables
[Video description begins] In T-SQL tab, the presenter modifies the code as follows: Code starts:
Line 1 CREATE TABLE [dbo].Users
Line 2 (
Line 3 [Id] INT NOT NULL PRIMARY KEY,
Line 4 username nvarchar(255) not null,
Line 5 password nvarchar(255) not null,
Line 6 salt nvarchar(255) not null
Line 7 )
code ends.
Code starts:
Line 1 CREATE TABLE [dbo].[Roles]
Line 2 (
Line 3 [Id] INT NOT NULL PRIMARY KEY,
Line 4 Role nvarchar(255) not null
Line 5 )
code ends.
Code starts:
Line 1 CREATE TABLE [dbo].[UserRoles]
Line 2 (
Line 3 Userld int not null foreign key references [User](id),
Line 4 RoleId int not null foreign key references [Roles](id),
Line 5 primary key (Userld, RoleId)
Line 6 )
code ends.
He then clicks the Update. A Preview Database Updates dialog box pops up. He then clicks the Update Database. The dbo.UserRoles[Design]* tab gets updated with the values written in the code.
So right click on Models, click Add, click New Item, select ADO.NET Entity Data Model, and for the model name, type MyHrEntities and click Add. Select EF Designer from the database and click Next. For the data connection, select MyHR.mdf. We’ll leave the connection stream the way it is and then click Next. I’ll open up tables and dbo. I’m going to click the check box next to tables. I’ll change the model namespace to dbcontext and then I’ll click Finish. So I have a new EDMX file that has a Roles table, a User table and a Comment table. I’ll take a look at some of the files that were generated as well.
The MyHrEntities.edmx[Diagram1] displays in the main pane. It contains three tables: Role, User, Comment. Role has a Properties section containing ID and Role1, and a Navigation Properties section containing Users. User has a Properties section containing ID, username, password, salt, and a Navigation Properties section containing Roles. Comment has a Properties section containing ID and Comment1, and a Navigation Properties section which is empty. Role and User are connected to each other.
Implement ASP.NET Core Identity

Securing the application is very essential aspect of any given application. With this infrastructure, we’ll be able to configure and program security much faster. In this video, we’ll simply understand the inbuilt feature and the way that the inbuilt feature has been organized. And how to configure this ASP.Net Core Security in our web application. To do this, I am to create an application. I have named it as ASPNETSecurityCore. I will be using ASP.NET Core Web Application. I’m doing this using Visual Studio 2017. Once we select this particular template, called ASP.NET Core Web Application, and click OK button, you will have a dialog box which pops up asking for various options in terms of creating ASP.NET Core Application. I am selecting the template Web Application MVC Controller. So once I select this Web Application MVC Controller, you have an option right below there, a button called as Change Authentication. By default, it is no authentication. So if you want to enable the authentication, then you could simply click on this Change Authentication button. By doing so, it pops up another dialog box called Change Authentication.
These authentications provide you varieties of where for you to configure the authentication and work with different authentication store or user store, in other words. We will simply go select Individual User Account. That is what we will look into as part of this particular session. And once we select Individual User Account, you will notice that there is a cover box where it shows you Store user accounts in-app. That means we will have the database configured, and it will be stored within the database that we want to take control upon, which is inside the application. Or we could also connect to an existing user store which is available on the cloud. In this example, of course, we will look into how to store it within the application. So I’ve selected the first option, and I would simply click on OK.
By doing so, it goes back to the previous dialog box which happens to be ASP.NET Core Web Application dialog box. Then, I click on OK button further on this dialog box, which is New ASP.NET Core Web Application. Whenever I do this, the default template will generate everything essential and necessary for us to enable the application, and also with the security features.
In the Solution Explorer, you can see there is this data. So there’s this Data folder that is created. Within the Data folder, you have Migrations and ApplicationDbContext. ASP.NET Security Core, by default in this case, makes use of Entity Framework. Entity Framework Core, to be more precise. The entity framework core provides you Code First approach. And this Code First approach can be configured from the viewpoint of a schema, a schema of the database. The way that you want to represent it can be represented in a Fluent API. The Migrations folder provides for it. You could see there is a file that is created with some couple of zeros and CreateIdentitySchema.cs.
Line 9 protected override void Up(MigrationBuilder migrationBuilder)
Line 10 {
Line 11 migrationBuilder.CreateTable(
Line 12 name: “AspNetRoles”,
Line 13 columns: table => new
Line 14 {
Line 15 Id = table.Column<string>(nullable: false),
Line 16 Name = table.Column<string>(maxLength: 256, nullable: true),
Line 17 NormalizedName = table.Column<string>(maxLength: 256,nullable: true),
Line 18 ConcurrencyStamp = table.Column<string>(nullable: true)
Line 19 },
code ends.
And likewise, it has got for every single table that is required. We could always reconfigure this and change it according to our need, but I am moving forward with the existing one in this particular video. So that’s the first part, where we have what are the tables needs to be created and the structure of the tables is defined within this particular file. The next thing, we have ApplicationDbContext file. As you can see in this Solution Explorer, we have the ApplicationDbContext.cs. The applicationDbContext.cs file.
Code starts:
Line 1 using System;
Line 2 using System.Collection.Generic;
Line 3 using System.Text;
Line 4 using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
Line 5 using Microsoft.EntityFrameworkCore;
Line 7 namespace ASPNETSecurityCore.Data
Line 8 {
Line 9 public class ApplicationDbContext : IdentityDbContext
Line 10 {
Line 11 public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
Line 12 : base(options)
Line 13 {
Line 14 }
Line 15 }
code ends.
As you could see, that ApplicationDbContext file is inheriting from the IdentityDbContext. So let me close this file.
The next thing is this migration will have to be executed for the database to be created. If the database does not exist, then the migration will automatically create the database. But if the database does exist, it’ll simply append it or create these tables. But if these tables are preexisting, then we will have to come up with another migration. So in this case, let’s go and look into how this database is supposed to go get created. So to do that, we have this appsettings.json file that’s been created. So if I double-click on appsettings.json file,
Code starts:
Line 2 “ConnectionStrings”: {
Line 3 “DefaultConnection”: “Server=(localdb)\\mssqllocaldb;Database=aspnet-ASPNETSecurityCore-B1F5DFC3-B114-4448-9C35-C27D997DE80A; Trusted_Connection=True;
Line 4 },
Line 5 “Logging”: {
Line 6 “LogLevel”: {
Line 7 “Default”: “Warning”
Line 8 }
Line 9 },
Line 10 “AllowedHosts”: “*”
Line 11 }
code ends.
The ConnectionStrings, the default connections, has a server. By default, I have a express edition the database that comes prepackaged as part of the Visual Studio. It works with that particular SQL server database instance. So in my case, it is (localdb)\\mssqllocaldb. And the database will be pointing to name of the project, whatever has been created with GUID to make sure that is unique. And we could always replace this.
So I am simply going to replace this. I’ll simply call it as EmployeeDb. By doing so, I’ll save it. And instead, this particular connection string will be taken for applying the migration. Let’s now look into how to go and apply the migration. To do that, let me click on the Tools menu that is available as part of the Visual Studio. Inside the Tools menu we have get NuGet Package Manger. In the NuGet Package Manager, you have Package Manager Console. In the Package Manager Console, once it gets opened, you can go and type in Update-Database and press on Enter. By doing this, the Package Manager will simply execute the migration. And thereby creating the database. So you could see that it initialized the ApplicationDbContext.
It’s connecting to the database and executing it. At this point in time, the database should have got generated. And also, necessary tables would be created. So I could see when I go to localdb/microsoftlocaldb, the instance, and I’ll just go to the database and refresh it.
So when I click on Refresh you could see that it created something called EmployeeDb. When I expand it and look into the tables, you could see all these tables that was there available as part of the Fluent API that was present in the migration has now been executed and the tables have been created.
At this point in time, this particular project is enabled with the security infrastructure. So let me click on the Close button and close the JSON file. Let’s go on to the Controller. So inside the Controller you have Home Controller, which is the default. There is no changes into it. Let me execute this particular program by clicking on this tab button.
Beside you will also have this hyperlink called Register and Login that is enabled. That is because ASP.NET Identity Core has enabled the security for individual account. There is an option called Register. When I click on Register, you will have a page that will ask you to create an account. So if I go to Email ID, these Email IDs and everything would be already validated as part of Fluent API, which we could change the way that it should validate. The validations can be relaxed or increased through the configuration. D-E-M-O. I would simply type it as demo@ezl.com, some e-mail ID that should match the pattern. Let me type the password. So I’ve typed the password which was been given, and I have retyped the same password in terms of confirm password. And after doing so, I just click on Register. The minute I click on the Register button, it not only registers that particular account in the sense it will have actually inserted the account into the data base, and it also logs in.
Code starts:
Line 8 using Microsoft.AspNetCore.Authorization;
Line 10 namespace ASPNETSecurityCore.Controllers
Line 11 {
Line 12 [Authorize]
code ends.
In his explanation, he points to line 8 and 12.
Now, instead the controller, I have enabled all those action methods to be authorized. So you will not be able to view it unless until you log in. This Authorize attribute can be annotated or decorated onto the controller or to an individual method. You can always do it onto the larger scope. And whichever method you don’t want it to be authorized, you can use Allow by enabling this attribute, AllowAnonymous.
Code starts:
Line 20 public IActionResult About()
Line 21 {
Line 22 ViewData[”Message”] = “Your application description page.”;
Line 24 return View();
Line 25 }
code ends.
You are escaping authorization by annotating AllowAnonymous. So, let me decrease the size of SQL Server Object Explorer. Let me click on the Start button to execute the program. And you could see that earlier we had the Home page. Right now, you could see that it redirected to the Login page. And I will have to simply enter username and a password. So I have typed in Email ID that happens to be the username, and the password, and I would simply click on Login. And now, you could see that there is this cookie policy that has been enabled.
Code starts:
Line 37 services.AddDbContext<ApplicationDbContext>(options =>
Line 38 options.UseSqlServer(
Line 39 Configuration.GetConnectionString(“DefaultConnection”)));
Line 40 services.AddDefaultldentity<IdentityUser>()
Line 41 .AddEntityFrameworkStores<ApplicationDbContext>();
Line 43 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
code ends.
Authentication Using Azure Active Directory

So when that is implemented by Active Directory, it makes it easy for different applications, devices to integrate with the Active Directories. Let’s understand the basic workflow of what truly happens when you use an Active Directory.
In an Active Directory, Active Directory acts as an identity provider. So a user can register himself with the Active Directory. It enables a concept called a single sign-on. In other words, broker authentication. This single sign-on ability is when you can log in to multiple websites or access multiple application with one single credential. And Active Directory does provide that particular option. In this workflow, as you could see, that uses the browser and signs in to an Active Directory. And the user then gets security token. And having that particular token, he can then access different other web application, which the Active Directory provides access to. An application that wants to subscribe to the authentication will be registered with the Active Directory. So Active Directory provides a means for you to go and enable different varieties of applications to go and integrate it in one single platform. And enable the resources to be accessed by these platforms and applications.
So I could see that we will have a browser with a single-paged application or browser-based application, with a web application that can have an access. Or the native applications are our mobile clients that wants to access can also have an access to this authentication, or it can authenticate them. Or any kind of a devices that runs as a background, part of it can also access the sites. Web APIs can make use of it, and the web application. So any of these things that wants to provide the access to the other applications or services can make queues offered through the Active Directories. So Active Directories provides this support for authentication for varieties of modern applications, which are dependent on industry standard protocol, such as OAuth and OpenID Connect. As part of Active Directory version 1.0, we have different varieties of application types that it supports.
Azure Active Directory B2C

Working with any application, an application would always require to have a security. Now having a security can be of two types. One is it could be taken care by the application builder. He has his one security store, and he would take care of the authentication and creating a registration page to register the user. Two is application data. But doing as such would be a very difficult task from the viewpoint of an end user. If an end user has to create many credentials and keep track of those credentials for every single given application, it really becomes very difficult.
In assets there are many scenarios where a user may not really want to go and register it with given application. And also find it comfortable for them to provide all the information that the website would really want to. That’s one part. The second part of the story is there are millions of users who wants to go and access an application. And you cannot really keep your application obstructed just because of making the user signing into your application.
So what is a viable or possible option? There are lots of third-party providers, such as a Facebook or a Google or Yahoo or Microsoft, they provide an ability for you to log in using their credentials store. In other words, it’s called single sign-on, or you also call it as a brokered authentication. So in this case, the Active Directory, which was already built for and being used for authentication, and been popularly used by many of the application. But the Active Directory, again, is something which we have to configure and make use of it to log in and take care of it.
So how would it be if in case having an application which I have to sign in and take care of it from the other identity providers, such as Google or Facebook, any of these identity providers? If you have to go and integrate your application with these providers, you will have to, again, go and keep working on it for every single application that you do. Now Microsoft and the business, too, there is B2C as an Active Directory. It has brought in a fantastic solution. Using Azure AD B2C, it will automatically take care of working with those identity providers. If there is any upgradation in terms of the protocol or any as such, it will be taken care automatically.
So that liberates the developer to simply focus on the application creation and the rest will be taken care by Azure AD B2C. In this video, we will see how to go and create an application and look at the workflow aspects or configuration features that is made available as part of business2C. So to do that, I have launched Azure Portal. Within the Azure Portal, I have already gone into the Azure Active Directory B2C Overview. So fastest, we have Applications as one of the options under the Manage.
So I’ll click on Add. And I will call it as SkillDemoApp. Now, the application would be including the web API, that I would say, Yes. Because it is going to be the RESTful. So the next thing that comes into the picture the minute I say yes, and also, does it include implicit flow? Which is automatically set to true. So now you could have a Reply URL. It’s a URL when the application is successful that it should route back.
So in this particular case. So I’ve just given a URL which can always be rewritten or can be modified later. So I’ve just copy pasted whatever I had it here. I’ll just click on Create. So you could see that it has created and I have that as SkillDemoApp.
Then the next thing is about identity providers. You have varieties of identity providers that’s made available. One is you have the email ID. You just want to know like, you know, if a person is using this particular email ID, it’s good enough for him to go with. Or you can just do that as the email ID.
Or it could also go in for the social identity provider. So let me go click on it. Let’s say I just click on and type in as FacebookProvider. So I could see that you have all the providers that social identity providers are available. You can choose any of the provider that you want to and then click OK for that one.
So use to set up the identity provider. All you need to do is provide a client ID and the secret ID. And I click OK for that.
So just click on Create. So you can see that you have the identity provider that has come into picture.
So you could also have custom identity providers. It works with O authentication and OpenConnect protocol. So any identity providers or social identity providers will provide the ability for you to go and connect. Anything that’s been followed with the O authentication will be automatically made available.
Azure Active Directory B2B

In this exercise, we’ll understand what is Azure Active Directory Business to Business. In other words, it’s called as B2B. Usually, when an application is created, it will always have to be extended to the partners. In other words, no business process is isolated or individual. So every business process will have an associated business process.
So these business processes, in turn, will be usually in the form of an application to take care of that particular business process segment. So therefore it’s, for example, if you talk about a supermarket, the inventory procured by a supermarket will be from various vendors. And similarly, a supermarket itself will be a vendor for the customer to go and purchase. Maybe the supermarket is also going to make a sale through sub-agents, that is again possible.
Likewise, when you have different particular business processes that work with a different business associate, business partners, then authorizing them or enabling them to access your application or your content when you’re working on Azure directly what needs to be provided, what access needs to be given to them, is very important. It’s also even very challenging. In order to answer this particular issue or limitation, Microsoft Azure provides the ability for you to go and have business to business integration. In other words, it’s simply an Active Directory that you have a lot of resources that you put in, how you will be able to provide an access to the Active Directory, which could actually enable the collaboration between different vendors or different partners or business associates From the viewpoint of accessing it from the system directly. So to do that, we have to go to Active Directory. So let’s go to Active Directory. To do that, I have Azure Portal. And as part of the Azure Portal, we have this option called as Azure Active Directory > Users.
So you could always add a user to access this particular Active Directory with the permission that they have. Or you can also invite somebody as a guest, in the sense like they’re associates. They are not part of system but you simply want them to access the Active Directory in a meaningful way which you could also restrict them. So you can send out an email. For example, I have an email ID. And I could also type in some kind of an inviting like, please access this particular folder for you to access some kind of a detail or whatever it is. You can just provide a description based on the invitation, any personal message that you wanted to. I will simply leave it as hello, right? And I would simply say Invite.
Now, it is of course the email ID that you are sending an invite to, and you can wait for the person to come back, and they can read in for that invite. So I’ll just go to Google, you have an email that was sent out and the email provides the access. So it simply says that you have been invited to access application from the company name and all that stuff. So it just provides you the logo and if you have any icon, it just sends it to you. And it can say Get Started.
By clicking on Get Started, it’ll route you back to the Microsoft portal. So you will be able to go and access the Windows account, again, just type in the user name and password for the account that is being provided for. You will be granted a permission to access and you can also be restricted to certain aspects in terms of the Active Directory.
So by doing this, this enables a collaboration between different providers or partners. This can also be done for one organization to another organization. For this particular part, we had to look at how do you really invite an individual who does not really have any kind of a company or any kind of an account. That they do not have an Active Directory or anything like that and you want to go and enable the filtration. But then this could be a simple individual who are a small organization who is enabling or providing the business. But they’re available in the cloud or anything like that that you want to really go and integrate between one application to another. So with that said, this is a feature that’s been bought forward by Azure in the Active Directory called business to business collaboration.
Identity Management Using Session Cookies

In this exercise, we’ll have a look into how to go with the authentication cookie or enabling the authentication by using cookie. To do this, I’ve created the ASP.NET MVC core application, named it as cookie authentication sample, auth sample in short. And this is created using Visual Studio 2017. There are a bunch of things that needs to be configured, so let me walk you through sequentially explaining how the program has been configured and enabled. In the startup.cs file which is there as part of the solution explorer, when I double click on it, we have something called ConfigureServices.
Code starts:
Line 15: Configuration = configuration;
Line 16: }
Line 18: public IConfiguration Configuration { get; }
Line 20: // This method gets called by the runtime. Use this method to add services to the container.
Line 21: public void ConfigureServices(IServiceCollection services)
Line 22: {
Line 23: services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
Line 24:.Addcookie(options =>
Line 25: {
Line 26: options.LoginPath = “/Login/UserLogin/”;
Line 28: });
Line 29: services.AddMvc();
Line 30: } Line 32: //This method gets called by the runtime. Use this method to configure the HTTP.
Code ends.
Inside the ConfigureServices, I have this particular method that’s been added for cookie. That is done based on a call called as AddAuthentication. And I’ve called it as CookieAuthenticationDefaults.AuthenticationsSchema.
So this is the one that basically enables the cookie authentication part, as equal to that, this is part of Microsoft.ASP.NetCore.Authentication.Cookies.
So it’s part of the authentication, ASP.NetCore authentication namespace, which I have referenced right here. So you can see that I have Microsoft.Asp.NetCore.Authentication.Cookies, right?
So let’s look into the controller. So first and foremost, I have a controller which is the LoginController then the UserController. They are two things. The login controller is the one which provides you the workflow for me to login and also to register the user. So I could see that I have RegisterUser method and also UserLogin method. So the UserLogin method will allow me to log in, which will have a look into what happens behind the scene. I will explain what is the code written there, we’ll look into that.
So the next thing that comes into the picture is the UserController. The user controller class is one that has a method called as Logout and UserHome. So this is the option called as logout and UserHome. So this is the option that comes in a picture. This could be their available anywhere even into the home or wherever sensible, but I have made that available as part of the user. So you can see that I have a Logout method internally to which I’m calling. HttpContext.SignOutAsync is the method I’m working. That method will automatically sign out in the sense it’s going in to log off, okay? So after it signs out I just want it to redirect, so I redirected to that of the home page. So in the home I wanted to call index, that’s the redirect button. So I’ll just remove the break points which is not really required to go with.
So the next thing that I have done is the model. So if you look at the model, I have UserDataAccessLayer. In other words, the DB context I’ve just created inside this particular file, I’ve created a file called as UserDbContext. The UserDbContext is meant for me to go and communicate with the database, retrieve the data and store the log in details, right?
So for that is why I’m making use of it, called UserDbContext. So within the UserDbContext, I have created get connections string method. I also have a static property called as Configuration, which is of type IConfiguration, of course. So inside the GetConnectionString, I am going with the ConnectionStringBuilder. Once I instantiate ConnectionStringBuilder, I have a SetBasePath which I’m setting it to the current directory, that is the root directory of the application. And then I’m adding the JSON file, which is appsettings.json. And configuration.builder.Build, the minute I say that, I will have the configuration which we’ll read it from the configuration so then I can access the configuration. So this is basically for me to read the configuration.
I’ve embedded the ConnectionString. Now, the ConnectionString is pointing to the database. I have the database which is available under the localdb. I have a database which is created as employee database.
Inside the employee database, I have created table which is simply called User info. So let me go to the design model by clicking on View Designer. So you can see that it opens it up for the Design mode. What is that I have in this particular table is UserID which is a primary key, then I have FirstName, LastName and the password.
So these are all the fields that I have. The idea is simply to bring about custom store. So I just want to store it and I want to retrieve it according to the program that I would be writing. So this is the database that I would want to store the user details. Fine, so that’s about the table. Then I have created this DataAccessLayer. I’ve named it as UserDbContext. Inside this UserDbContext, one is the configuration. And then I have a method called RegisterUser. It is in the RegisterUser I will be accepting the user details and open up the Connection object, so I have the connection.
Create an instance of the connection object, then create an instance of a command. I’ve simply returned it as insert statement, right, which is parameters query of course, in this case. But this could also be written as storedreq if required but is not really needed to bring on the scenario that we are working with. So in this case, I have simply made as an insert command. If in case you are changing the database from one database to another database and if you want to have a flexibility, it’s always a good idea to write the statement directly and not to have too much of dependency on to the stored procedures.
Keeping that in mind, I have simply created that has DML Statement, then I have the parameters that are bounded. So in the command object I have cmd.Parameters.Add for these parameterized properties or these parameterized attributes that I had created. I need to resolve them. So that is what has been done with the parameters. So I’ve add it for individual values that I have collected as part of the object which comes in as the input for the method. And then Connection object gets opened, it establishes a connection and after that, I’m executing NonQuery. This is method which is for a failure document of course. And once that happens, the ExecuteNonQuery returns an integer variable, the integer indicates how many cards have got affected. So therefore, I want to check if it’s greater than 0.
If it’s greater than 0, then it is understood that successful. If it is not, then the Insert command has failed, somehow it did not change anything at all in the database. So keeping that as a result, I’m simply setting it out as a true or false, that’s a Boolean value. Similar to data for RegisterUser, I also have something called as ValidateUser. The ValidateUser accepts the user details. I’m connecting to the database and trying to find out if the username and password matches. This could be done in a much better way, I’m just doing this from the viewpoint of syntactical aspect. Therefore, I have not really taking care of so many things that needs to be taken care in a real application.
So in the very next line, I have the parameters query. I’m resolving the parameters. And after resolving the parameters, I’m trying and executing it with the ExecuteScalar method for the reason that I have said select count of star from the UserInfo. If at all it returns me any count at all, in this particular regard, it should return only one record, right? So I am just taking that as ExecuteScalar. If in case this happens again to be greater than 0, then the result is successful, that means there is a record available in the database. If not, there is no record available, that’s the idea. So I’ve just simply returned it as true. So calls enable this with the roles, and we could retrieve that role and accordingly take care. But I’m only taking care of the username and password in this case. So let me close the UserDataAccessLayer.cs file. Let’s close it, and go back to the LoginController.
So in the login controller, I have a RegisterUser, and in the RegisterUser, I’m in turn checking for the data, if in case the data is valid. That’s part of the model binder, and the model binder tells me whether the value is valid or not. If it is valid, I’m invoking that RegisterUser method. And I’m checking if it is registered. If it is registered, it is true or false. I’m clearing out and saying it is registered successfully or it is not successful.
Okay, so with that said, let’s go on to the UserLogin. Again, UserLogin is where the UserLogin would be called as HttpGet and the page will be presented. And after that, the pulse back has been handled by the user login. Again, so I bound it to the user details, right?
So once it gets bound to the user object which is of type UserDetails, I’ll be able to get the model details. In the ModelState, I’m just removing FirstName and LastName so that it may not be validated and I’m checking if it’s valid, of course it is going to be valid. So in the ValidateUser, I’m just passing this user because I only make use of username and a password. So FirstName and LastName, if at all there is any details being provided, I’m just eliminating it, or it is not required to be validated. Because I’m only checking for username and the password. So after it is set true or false, if it’s true then this is where I’m adding the claim.
Code starts:
Line 66; var claims new List<CIaim>
Line 67: {
Line 68: new Claim( ClaimTypes.Name, user.UserID)
Line 69: };
Line 70: Claimsldentity userldentity = new Claimsldentity(claims, “forms”);
Line 71: ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
Code ends.
So the claim object is getting instantiated, so to add the claim, it is a list of claim that it goes with. So I have created claims list of claim, added one single value in it. There’s a enum that is available called as ClaimTypes, which has got a name, I’m using that type, and I’m saying user.UserID. So that’s the data, I have it in terms of Claim. And on the identity part of what I’m doing it as forms, authentication or whatever the name that you wanted to give for that, it’s basically the login. And then after the identity is created in the Claims principle, this user identity has been added. And that becomes the credential or in other words, that’s a user principle.
Okay, another very important aspect is, let me rewind back to the Visual Studio. I have enabled authorize, so I can see that there is this particular attribute called as Authorize, I’ve enabled that as part of the controller. So only authorized user can access it.
So that means it’s not available for anonymous and similarly for also the user, it’s been assigned as authorized.
That is a reason, right, in the login page comes in specific on anything like home or about, you can see that it simply gets redirected.
So now, let’s go to the user ID and let’s go create it. First is, I have this sign page, so I’ll click on the login page and user, type it as user itself, john password. So I could see that the RegisterUser getd called and model has been type gets mapped. And it creates it from the database, because it’s an identity column, user ID will be automatically taken care.
So let me execute it because I explained the code already. So you could see that Registered Successfully. So we also happen to have an option called Click here to login. So when I click on it, it takes you back to the Login Page.
So here, I would enter the User, so I would say user. Password, I have typed it as demo. So when I click on it, so you could see that it redirects to that of the UserHome. Right, so you have a Home, About, all those options, pages that I can go with. That’s a default page, I have not really changed anything under the Home part. And we also happen to have this button called a Sign out.
So the minute I click on Sign Out, it just signed out. With that said, we had a look at how to go and configure authentication cookie, and how to go in and enable customer authentication.
Acquiring Access Tokens with MSAL

The bullet point under the title reads: Tool in .NET framework with which you can authenticate users to an on-premises Active Directory deployment or to the cloud
In this section, we’ll understand what is Microsoft Authentication Library and its usage. Microsoft Authentication Library, the actual full form for that is Azure Active Directory Authentication Library, ADAL in short. It’s basically a tool that’s provided for the developers who wants to make use of configuring to the Active Directory’s program. To take care of authentication onto the Active Directories or which could be on premises or on the Cloud.
So this gives the developers the ability to go and program. When working with authentication, there are certain things that needs to be taken care by the developer, which is now taken care by the authentication library such as the caching. It’s configurable tokens cache, right, that stores access token and refreshes the token automatically. It also makes sure that whenever the token expires, it’ll refresh that particular token when available. Also provides for asynchronous method calls.
Let’s take an example. If you look at it, how does it acquire the access token? When you have ASP.NET application, which is running on a web server, when a browser makes a request to a particular web server, that gets redirected to the Azure for the credential. And when there’s a prompt that comes in for the credential when it is entered, the Azure does the validation for that particular user and returns a token. And that token, whatever is there received by the browser, then will be able to provide for the ASP.NET web server. And based on that particular token, that web application can then provide an access for what the user wants to access.
Active Directory Authentication Library version 1.0 for Web Application is made available in two categories or two types. One is the client-side library, another one is server side library. On the client side, which is available as a JavaScript file, it goes with the ADAL.js file. And similarly on the server side, it supports an Open Web Interface for .NET. On the OWIN it provides the support for ActiveDirectory. And for OpenID Connect, and also WS-Federation, and also for Active Directory Passport.
The first bullet point reads: Microsoft-supported client libraries.
The sub bullet point reads: ADAL.js.
The second bullet point reads: Microsoft-supported server libraries.
The sub bullet points read as follows:
1 : OWIN for Azure AD,
2: OWIN for OpenlD Connect,
3: OWIN for WS-Federation,
4: Azure AD Passport.
These are the options for server side library. When can we exercise ADAL, Active Directory Authentication Library? When you want to make use of a native application programming that’s running on the device that needs to authenticate its user. Or when you want to authenticate the client application which is running on the web server. Or if you want to authenticate client application which is running on a server on behalf of a user, right, or impersonating the user.
A bullet point under the title reads: Authenticating.
The sub bullet points read as follows:
1: Users of a native client application running on a device,
2: Confidential client application running on a web server,
3: Confidential client application running on a server, on behalf of a user
With that said, we had a look at what exactly is Microsoft Authentication Library and the purpose of Microsoft Authentication Library.
Working with Custom UserStores Using Middleware

In this exercise, we will understand how to create a custom UserStore to store the user credentials. ASP.NET Core Identity is basically a membership system which provides you the ability to go and configure the web applications to provide registration page, login page, and password reset pages, and all those, the user datas.
It is very similar to that of what was added by Microsoft as part of ASP.NET 2.0. We had an ability to automatically generate the login pages, register pages, password reset, that is nothing but the authentication part of it, right? It was completely taken care where a user can take care of registering and also for signing in. The login pages were made automatically enabled.
So the same feature was available with ASP.NET MVC. Now, it is made available to the .NET Core, which is more precisely ASP.NET Core. It is available under ASP.NET Core Identity. UserStore providers provides the classes that allows you to store the user details and roles of these users. The details of users and roles are stored, and the structure for that particular thing is provided by the UserStore providers.
By default, ASP.NET Core Identity is implemented to store as part of SQL Server database and it works with Entity Framework core. The ability of ASP.NET Core Identity to go and extend it with the different store providers makes it possible to have a custom UserStore. So to do that, we have to implement two of the interfaces. Both of these interfaces provide the ability for you to take care of custom stores. The first one happens to be IUserStore and the second one is IRoleStore. IUserStore Interface provides the fundamental workflow that is required to have a user information managed.
Code starts.
namespace Microsoft.AspNetCore.Identity .
{
public interface IUserStore<TUser> : IDisposable where TUser : class.
Task<IdentityResult> CreateAsync(TUser, CancellationToken cancellationToken);
Task<IdentityResult> DeleteAsync (TUser, CancellationToken cancellationToken);
Task<TUser> FIndByIdAsync(TUser, CancellationToken cancellationToken);
<TUser> FIndByNameAsync(string normalizedUserName, CancellationToken cancellationToken);
Task <string> GetNormalizedUserNameAsync(TUser, CancellationToken cancellationToken);
Task<string> GetUserIdAsync(TUser, CancellationToken cancellationToken);
Task<string> GetUserNameAsync(TUser, CancellationToken cancellationToken);
Task SetNormalizedUserNameAsync(TUser, CancellationToken cancellationToken);
Task SetUserNameAsync(TUser, CancellationToken cancellationToken);
Task<IdentityResult> UpdateAsync(TUser, CancellationToken cancellationToken);} } Code ends.
IUserStore provides methods such as create which will allow you to create a particular user, and delete a user, find user by ID or name, and also to get user ID or get user name. And all those methods are also supposed to be implemented and provided. It also has a method called SetUserName and UpdateUser. So these are all the methods that must be implemented as part of IUserStore,which is of a particular type. The Tuser will be the type that definitely must be class. This particular class called as IUserStore is a part of Microsoft.ASP.NetCore.Identity. Furthermore, if you look at it, we have IUserRoleStore. As you could see that the IUserRoleStore itself integrates from IUserStore.
A slide titled IUserRoleStore is displayed.
Code starts.
namespace Microsoft AspNetcore.Identity
{
public interface IUserRoleStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class.
{
Task AddToRoleAsync(TUser user , string roleName, CancellationToken cancellationToken);
Task<IList<string>GetRoleAsync(TUser, CancellationToken,cancellationToken);
Task<IList<TUser>>GetUsersInRoleAsync(string roleName, CancellationToken, cancellationtoken);
Task<IList<TUser>>IsInRoleAsync(TUser,string roleName, CancellationToken, cancellationtoken);
Task<IList<TUser>>RemovefromRoleAsync(TUser,string roleName, CancellationToken, cancellationtoken);
}
}
code ends.
When you have IUserStore which of course takes care of the users, plus you want to enable the role-based user management, then you could implement IUserRoleStore which provides you AddToRole, GetRoles, GetUsersInRole, IsInRole, and RemoveFromRole. So these are the methods that must be implemented in order to take care of IUserRole. And that automatically takes care of the role management part of custom UserStore. With that said, we understood what is a custom UserStore and how to implement custom UserStore using the interfaces such as IUserRoleStore and IUserStore.
Testing a SQL Membership Provider

Code starts.
Line 1 using System;
Line 2 using System.Collections.Generic;
Line 3 using System.Linq;
Line 4 using System.Web;
Line 5 using System.Web.Mvc;
Line 6 using MyHR.Lib;
Line 7 using MyHR.Models;
Line 8 using MyHR.Models.View;
Line 9 using System.Web.Security;
Line 11 namespace MyHR.Controllers
Line 12 {
Line 13 public class AccountController: Controller
Line 14 {
Line 15 Get: Login
Line 16 [HttpGet]
Line 17 public ActionResult Create()
Line 18 {
Line 19 UserDto user = new UserDto();
Line 21 return View(user);
Line 22 }
Line 24 [HttpPost]
Line 25 public ActionResult Create ( string Username, string Password)
Line 26 {
Line 27 string message = “”;
Line 28 MembershipCreateStatus status ;
Line 30 try
Line 31 {
Line 32 if ( Username== null || password== null || Username.Length<1 || Password.Length<1 ) code ends.
In this section, we’re going to test the operation for a SQL membership provider in an ASP.NET MVC web application in Visual Studio 2017. We’re going to use an existing website called MyHr, and we are going to use the authorize attribute in some of the controllers. So to start, I’m going to open the comment controller, I have an action called Create. I want to modify this so that only authorized users can create new comments.
I’ll click on Create Username again. This time I’ll type csmith, then I’ll type password. Then I’ll click on Create.
I’m going to start to add a comment now. So click on Comment, click Add New Comment. So because I have the authorized attribute, I have to log in.
So I’ll try typing in ssmith and password and then I’ll click on Login. So I’m now logged in, and I can add a comment.
I’ll type, this is a new comment. And I’ll click Create. So now that the user is logged in and authenticated, they can add comments. I’ll close the browser, and I’ll go back
I’m going to go back to the comment controller. I want to change the authorize tag so that only ssmith can create new comments. Type (Users = “ssmith”). Copy line 29 and paste it on line 39. Click on the Save All icon and then, start the application in Internet Explorer. I’m going to add a comment again, so click Comment.
Click Add New Comment. I need to log in, so I’ll try logging in as csmith. So this time, when I log in as csmith, I’m not able to add a new comment.
Let’s try logging in as ssmith. I’ll type ssmith as the username, I’ll type password for the password, and then I’ll click on Login. So now I can add a comment. I’ll type test comment and then I’ll click on Create. In this video, we tested the operation of a SQL membership provider in an ASP.NET MVC web application in Visual Studio 2017. We modified an existing application called MyHr and added authorize attributes to the custom controller. We then tested everything using Internet Explorer.
Create Custom Membership Providers

In this exercise, you will create custom membership providers. You will configure a SQL Membership Provider, set up a SQL Membership provider Model, and test a SQL Membership Provider. Now pause the video and perform the exercise. Let’s take a look at how I would perform this exercise. So to start, I’m going to create a new custom membership provider.
So we click on Lib, click Add, click Class. For the class name, type CustomMembershipProvider,
[Video description begins] In Solution Explorer tabbed pane, the presenter right-clicks the Lib sub-folder under MyHR folder.
He selects Add from the context menu and selects Class from the fly-out menu. An Add New Item – MyHR dialog box is displayed.
There is a list of items with Class option selected. The Name field is populated with Class1.cs.
Code starts:
line 1 using System;
line 2 using System.Collections.Generic;
line 3 using System.Linq;
line 4 using System.Web;
line 6 namespace MyHR.Lib
line 7 {
line 8 public class CustomMembershipProvider
line 9 {
line 10 }
line 11 }.
Code ends.
On line 8, add colon, then type MembershipProvider. There’s an error message.
Code starts:
line 8 public class CustomMembershipProvider : MembershipProvider. Code ends.
The error message displays: The type or namespace name ‘MembershipProvider’ could not be found (are you missing a using directive or an assembly reference?) Show potential fixes (Alt+Enter or Ctrl+.) .
A light bulb is displayed besides it.
So click on the light bulb, then click on the top line.
There’s an error message for CustomerMembershipProvider. So we’ll look at CustomerMembershipProvider. We’ll click on the light bulb, and we’ll say ImplementAbstractClass.
A new page of code, CustomMembershipProvider.cs is displayed.
So by clicking on that we added a bunch of stubs, and we still need to go and add some code. So we’ll go up to the top, we’ll just kind of see the stuff that’s in here. We’re not going to implement all of this because it would take too long, but we’re going to look at a few of the main ones. We’re going to look at CreateUser.
line 43 public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
line 44 {
line 45 throw new NotImplementedException();
line 46 }. CODE ENDS. [Video description ends]
I’m going to delete line 45. I’ll add a comment, I’ll just say, CreateUser. I’m going to scroll to the top of the page and add some library references. On line 6, type using MyHR.models. On line 7, type using MyHR.models.repository. On line 8, type using MyHR.models.view.
Code starts:
line 1 using System;
line 2 using System.Collections.Generic;
line 3 using System.Linq;
line 4 using System.Web;
line 5 using System.Web.Security;. Code ends.
He then adds the following code after line 5: Code starts:
line 6 using MyHr.Models;
line 7 using MyHr.Models.Repository;
line 8 using MyHR.Models.View;.
Code ends.
I’m going to go back down to the CreateUser command. On line 49, type UserDto user = new UserDto. On line 51, type var salt = Security.CreateSalt. Into the parameter, I’ll type 128 = username. On line 53, type user.Password = Convert.ToBase64String. In the parenthesis type Security.Hash, in the parenthesis type username and type salt. On line 54, type user.Salt = salt.
line 48 //Create User
line 49 userDto user = new UserDto();
line 51 var salt = Security.CreateSalt(128);
line 52 user.Username = username;
line 53 user.Password = Convert.ToBase64String(Security.Hash(username, salt))
line 54 user.Salt = salt;. Code ends. [Video description ends]
I need to create a new user repository, so let’s go to the top of the page and create it. On line 14,
Code starts:
line 12 public class CustomMembershipProvider : MembershipProvider
line 13 { . CODE ENDS. [Video description ends]
type UserRepository_userRepository = new UserRepository.
Code starts:
line 14 UserRepository _userRepository = new UserRepository();. Code ends. [Video description ends]
I’ll go back down to CreateUser. On line 58, type _userRepository.update(user). On line 60, type return user. I have an error message, status must be assigned. So for now on line 60, I’ll type status = MembershipCreateStatus.Success.
Code starts:
line 58 _userRepository.Update(user);
line 60 status = MembershipCreateStatus.Success;
line 62 return user;. code ends. [Video description ends]
I’m going to scroll down to ValidateUser. I’m going to delete line 127. So on line 127 type var user = _user Repository.GetUser(username);. We’re going to hash the password using the stored salt, so type var hashedPassword = Security.Hash. In the parenthesis type password comma, user.salt. On line 130, type return user.password = convert.ToBase64String, and in the parameters type hashedPassword. And I have an error message, so I need to go and add a second equal sign. I will click on the Save All icon.
line 125 public override bool ValidateUser(string username, string password)
line 126 {
line 127 throw new NotImplementedException();
line 128 } . CODE ENDS. He deletes code in line 127 and replaces it with the following code: Code starts:
line 127 var user = _user Repository.GetUser(username);
line 129 var hashedPassword = Security.Hash(password, user.salt);
line 130 return user.password = = Convert.ToBase64String(hashedPassword);. Code ends.
He then saves the code. [Video description ends]
I need to modify CreateUser so let’s scroll back up to CreateUser. On line 55, I need to change username to password. Since we’re actually going to encrypt the password not the username,
Code starts:
line 55 user.Password = Convert.ToBase64String(Security.Hash(username, salt));. Code ends.
He modifies the code in line 55 as follows:
line 55 Code starts: user.Password = Convert.ToBase64String(Security.Hash(password, salt));. Code ends.
that was a mistake I had made. So now I need to modify the Web.config file. I’m going to open Web.config by double-clicking on it,
[Video description begins] The presenter navigates to the Solution Explorer tabbed pane and double-clicks the Web.config file.
The Web.config file is displayed.
type authentication mode = “Forms”. On line 19, type forms login URL, type ~/Account/Login. Type timeout, type 2800, and then type my >. On line 21, type membership, type defaultProvider, type MyMembershipProvider. Type providers, type clear, type add, type name. And type MyMembershipProvider, type type=”MyHr.Lib.CustomMembershipProvider”.
[Video description begins] In the Web.config file, the presenter scrolls to the following section of code: code starts:
line 17 <system.web>
line 18 <compilation debug=”true” targetFramework=”4.6.1” />. CODE ENDS.
After line 17, he enters the following code: Code starts:
line 18 <authentication mode=”Forms” >
line 19 <forms loginUrl=”~/Account/Login” timeout=”2800” />
line 20 </authentication>
line 21 <membership defaultProvider=”MyMembershipProvider”>
line 22 <providers>
line 23 <clear/>
line 24 <add name =”MyMembershipProvider” type=”MyHr.Lib.CustomMembershipProvider” />
line 25 </providers>
line 26 </membership>. Code ends.
I’m going to look at the AccountController now. I’m going to add code for creating users. So on line 39, type Membership.CreateUser(Username, Password, “”, “”, “”,) I’ll type true. I’ll type out status and a semi colon. I’m going to add code to the login action, so scroll down.
line 39 Membership.CreateUser(Username, Password, “”, “”, “”, true, out status);.
code ends.
We will change line 83 to Membership.ValidateUser. And we’ll type Username and Password. I’m going to click on the Save All icon.
Code starts:
line 53 var login = true;. CODE ENDS.
He changes the code in line 53 as follows: Code starts:
line 53 var login = Membership.ValidateUser(Username, Password);.
Code ends.
I’ll right-click on Web.config, and click on Close all documents. I’m going to open the CommentController, and
I’ll take a look at the Create actions. And the Create action has Authorize attributes.
line 28 // GET : Comment/Create
line 29 [Authorize]. Code ends.
There is a toolbar with options: Application name; Home; About; Contact; Login; Comment.
He clicks the Login option. A login page with Username and Password fields and a Create Username link displays.
He clicks the Create Username link.
So I’ll click on Create Username. I’ll type ssmith, and I’ll type password for our password. And then I’ll click on Create. I’ll click on Create Username again.
He then clicks create. A message displays: Account created for ssmith !.
The screen reverts to the login page.
This time I’ll type csmith, and I’ll type password. Then I’ll click on Create.
In the Create page, he enters the username as csmith and password as password.
He then clicks create. A message displays: Account created for csmith !.
I’m going to start to add a comment now. So click on Comment, click Add New Comment.
The Comments page is displayed. It contains the following three comments: this is a test; This is a new comment; and comment2.
It also contains a link: Add New Comment.
So because I have the Authorize attribute, I have to log in. So I’ll try typing ssmith and password, and then I’ll click on Login. So I’m now logged in, and I can add a comment.
I’ll type, this is a new comment. And I’ll click Create.
So now that the user is logged in and authenticated, they can add comments. I’ll close the browser. And I’ll go back and take a look at the database tables. I’ll right-click on Users. I’ll click Show Table Data.
The dbo.Users[Data] page displays.
There is a table with columns Id, username, password, salt.
There are three rows : The first is: Id = 2; username = ssmith; a password; and salt.
The second is: Id = 3; username = csmith; a password and salt.
The third is an empty row with Id = NULL ; username = NULL ; password = NULL ; salt = NULL
I’m going to go back to the CommentController. I want to change the authorize tag so that the only ssmith can create new comments. Type (Users = “ssmith”), copy line 29 and paste it on line 39.
Code starts:
line 28 // GET : Comment/Create
line 29 [Authorize]. Code ends.
He changes the code in line 29 as follows: Code starts:
line 29 [Authorize(users = “ssmith”)]. CODE ENDS.
He copies this line and scrolls down to the following section of code:
line 38 [HttpPost]
line 39 [Authorize]
line 40 [ValidateAntiForgeryToken]. CODE ENDS.
He replaces the code in line 39 as follows: Code starts:
line 39 [Authorize(users = “ssmith”)]. Code ends.
Click the Save All icon, and then start the application in Internet Explorer. I’m going to add a comment again, so click Comment. Click Add New Comment. I need to login, so, I’ll try logging in as csmith. So this time when I log in as csmith, I’m not able to add a new comment. Let’s try logging in as ssmith. I’ll type ssmith as the username, I’ll type password for the password, and then I’ll click on Login. So now I can add a comment, I will type test comment, and then I’ll click on Create. And the new comment was added. In this exercise, we created a new custom membership provider. We created a custom SQL Server membership provider, set up a SQL Server membership provider model, and then tested the SQL Server membership provider. ASP.NET