MVC 5

Identity Server: Introduction

In the SPA based sample applications, this blog has used so far user authentication has either been completely ignored in order to keep the examples simpler or the sites have used ASP.NET Core’s built in identity to encapsulate the whole SPA. In this post (or series of posts) I am going to share what I learn along the way of creating an Angular (2+) application that utilizes ASP.NET Core as its host/API/backend.

This post isn’t going to cover any code it is just going to be a lot of the information I gathered in the process of learning more about Identity Server.

Following are all the post in this series.

Identity Server: Introduction (this post)
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

Identity Server

According to their docs IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core which enables Authentication as a Service, Single Sign-on, API Access Control and a Federation Gateway.

Obviously, that covers a lot of scenarios. The two that I am interested in are Authentication as a Service and the API Access Control which has driven my research which means that the other aspects of IdentityServer4 will not be included.

Official Samples

The IdentityServer GitHub account has a samples repo that contains a ton of examples. I have found the quickstart area of the repo to be the most helpful when starting out.

Based on all the quickstarts samples it looks like a typical setup involves a minimum of three projects. One for the API, one for the client and one for Identity Server. As you go through the samples the number of projects increase, but that is because of a wider range of scenarios that the sample is trying to cover.

References for learning

Damienbod has a whole series of blog posts related to IdentityServer4 and code to go along with it which can be found here. As a side note if you are interested in ASP.NET Core and you aren’t following damienbo you should be he has a ton of great content.

Blog posts
Videos

Identity Server Alternatives

Identity Server isn’t the only way to go there is a number of Software as a Service options that cover a lot of same scenarios. The following are some examples.

Auth0 – Check out the .NET Core related blogs by Jerrie Pelser
Stormpath
Amazon Cognito

Wrapping up

Obviously, I didn’t get a lot covered on how to actually do something with IdentityServer, but I wanted to share my starting point. This is an area I am going to continue digging it to and sharing information about as I learn more.

If you have any resources in this area please leave a comment below.

Identity Server: Introduction Read More »

OAuth 2.0 with Google

After getting Basic Authentication and Authorization working I thought it would be neat to add login via Google which involves using OAuth 2.0. To get started I used NuGet to update all the OWIN related packages in my project. I ran across some people who had issues with older versions of OWIN so I recommend getting the latest to avoid any potential problems.

Some third parties require SSL when using their auth services so I decided to go a head and change my application to use SSL. I hit a couple of issues during this part of the process that I want to point out. The first is that when you change to SSL IIS Express defaults to using port 44300. I missed this the first try and it took a good bit of searching before I spotted the problem. Even after reverting all my changes I could not get my site to load without errors. A reboot got my reverted site working which I am assuming was a configuration issue with IIS Express that got reset on reboot.

To enable SSL select the project in Solution Explorer and press F4 to bring up the properties window (which has different options that the project properties you get if you right-click the project and click properties). Set the SSL Enabled property to true. Copy the SSL URL to use when updating the project.ContactsPropertiesSsl

Back in the Solution Explorer right-click on the project and click properties. On the Web tab under the Servers section paste the SSL URL from above into the Project Url and save.ContactsProjectPropertiesSslUrl

When running the first time after enabling SSL Visual Studio will prompt asking if you would like to trust the self-signed certificate that IIS Express generated. I chose to trust in order to avoid warnings from the browser.

OAuthTrustIISSSL

The last change need in the project is in the Statup.Auth.cs found in the App_Start folder. In the ConfigureAuth function add the following code using your own ClientId and ClientSecret.

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "Your Client ID",
    ClientSecret = "Your Client Secret"
});

If you don’t have a client ID and client secret head to the Google Developers Console. The first step in the process is to Click the Create Project button.

GoogleDevelopersConsoleEnter a project name and project ID. The refresh button on the project ID field will randomly generate project IDs in case the one you want is already in use. When finished click Create.
GoogleDevelopersConsoleNewProjectAfter the project creation process finishes click on the name of your project. Next click on the APIs & auth section and then click the Consent screen option. This set of options determines what the user sees when Google prompts a user for consent to use information from their Google account. The minimum needed is email address and product name. For a live application I would recommend filling out as much as possible to give the user the best experience. When done click Save.GoogleDevelopersConsoleAPIsAndAuthConsentScreenIn the same APIs & auth section click the APIs option. Search for Google+ API. Click the name Google+ API and on the next screen click Enable API.GoogleDevelopersConsoleAPIsAndAuthApisGooglePlusAgain in the APIs & auth section click on Credentials option and then in the OAuth section fo the page click Create new Client ID.
GoogleDevelopersConsoleAPIsAndAuthCredentialsThe following dialog will show. Select the appropriate Application type which is Web application for this example. For Authorized JavaScript origins use the value from Project Url listed above which in my case is https://localhost:44300/. For Authorized redirect URIs the base URI is the same but with an added level. For MVC 5 the redirect should be set to https://localhost:44300/signin-google changing the base URI as needed of course. Click Create Client ID and you will be returned to the previous page that will now list the Client ID and Client Secret needed in Statup.Auth.cs.
GoogleDevelopersConsoleAPIsAndAuthCredentialsCreateClientId

Now the login page will have a button for Google which will allow users to create an account and associate it with their Google account. After the association users will be able to login with their Google account.LoginWithGoogle

 

From this point adding Microsoft, Facebook or Twitter would just be a matter of adding the desired options to ConfigureAuth Startup.Auth.cs and going to each service and requesting API access.

OAuth 2.0 with Google Read More »

Basic Authentication and Authorization

When I created my contact application I did so with authentication set to Individual User Accounts as seen below.
vs2013NewAspProject

 

By choosing an authentication option during project creation Visual Studio takes care of a lot of the work involved with getting authentication and authorization up and running. For individual user accounts the default data store is SQL and Visual Studio sets up the need classes and data using entity framework to create a database and the needed tables to store authentication data. An AccountController and associated views are also created to handle user creation and login.

I am not going to cover everything that Visual Studio created automatically. I will be walking you through the other changes are needed to start using authentication and authorization with all the bits Visual Studio has provided.

The first step is to add AuthorizeAttribute to the FilterConfig which is found in the App_Start folder.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthorizeAttribute());
    }
}

Now that the AuthorizeAttribute is added to the applications filters any page that is requested by a user that is not authorized will be redirected to a login page to authenticate.

With authorization and authentication now in play any controller action that should allow anonymous usage will need to have the AllowAnonymous attribute added. The following example is using AllowAnonymous on the index action of the home controller.

public class HomeController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }
}

That is all there is to get the very basics going. This is a big subject, but Visual Studio and .Net do a lot of work to make getting basics up and going simple.

Basic Authentication and Authorization Read More »

Adding Paging

As the number of contacts grows it is overwhelming to see in single page. To address this I am going to add paging to the contact list and only show 10 contacts per page.

To generate a large set of realistic date I am using Mockaroo. They offers data in CSV, Tab-Delimited, SQL, Excel, JSON and DBUnit XML with up to 1,000 rows of data per generation for free. The data Mockaroo is way better than the crazy stuff I was coming up with. If you need more than 1,000 rows at a time they do have a pay option.

For paging I am going to take advantage of the PagedList.Mvc NuGet package. Using the package manager console it can be installed with the Install-Package PagedList.Mvc command as seen in the following screenshotPackageManager-PagedListMvc.

To start using PagedList.Mvc I need the following changes to ContactsController. Add new using for PagedList and the index action needs a page parameter. As part of this change I also refactored the contact query to the GetContacts function so the Index action is much less cluttered than before. The function is now shown below but I moved the distinct city query to the GetDistinctCities function.

        
public ActionResult Index(string filterCity, string filterSearch, int? page)
{
    ViewBag.filterCity = filterCity;
    ViewBag.filterSearch = filterSearch;
    ViewBag.city = new SelectList(GetDistinctCities());

    var contacts = GetContacts(filterCity, 
                               filterSearch)
                   .ToPagedList(page ?? 1, 10);

    if (Request.IsAjaxRequest())
    {
        return PartialView("_ContactList", contacts);
    }

    return View(contacts);
}

private IQueryable<Contact> GetContacts(string city, string search)
{
    var contacts = from c in db.Contacts
                   select c;

    if (!string.IsNullOrWhiteSpace(search))
    {
        contacts = contacts.Where(c => c.Name.Contains(search));
    }

    if (!string.IsNullOrWhiteSpace(city))
    {
        contacts = contacts.Where(c => c.City == city);
    }
     return contacts.OrderBy(c => c.Name);
}

Notice that I am now saving the parameter values of the city and search filters to the ViewBag in the index action which will be used when changing pages when a filter is in play.

In GetContacts I had to add an order by statement to the contacts being returned. This is to make sure the list is always in the same order. It will also be a good spot to add different ordering options in the future.

The last change in the Index action was to take the return value from GetContacts and call ToPagedList on it. This function takes a page number and number of items per page and returns a paged list as the name implies. In my case if page is null I am using page 1 and each page will contain 10 items.

In both Index.cshtml and the partial view _ContactList.cshtml the models need to be changed to PagedList.IPagedList. In addition @Html.DisplayNameFor also needs to be changed from model.Name to model.FirstOrDefault().Name. The last step is to add the paged list control to the bottom of the view. Here is the code from the contact list partial view.

@using PagedList.Mvc
@model PagedList.IPagedList<Contacts.Models.Contact>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().State)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().ZipCode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Country)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.State)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ZipCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>

@Html.PagedListPager(Model,
                     page => Url.Action("Index",
                                        "Contacts",
                                        new { ViewBag.filterCity,
                                              ViewBag.filterSearch,
                                              page }),
                     PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
                          new AjaxOptions
                          {
                              HttpMethod = "GET",
                              UpdateTargetId = "contactList"
                          }))

The Url.Action on the PagedListPager is the function that will be called when the user want to changes pages. Index is the action that will be called, Contacts is the controller that the action will be called on. Next is an anonymous type that will be processed to determine what parameters the index action will be called with. It is important that the existing filters are passed to the index action or else when the pager requests a different page it will return all contacts instead of next page of the filtered set of contacts.

The other nice option that the PagedListPager offers is the option to use ajax when requesting a different page. Since the contact page is using ajax when filtering it would be silly not to do the same when paging. To enable ajax just use the PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing with the same AjaxOptions as the filter form.

As a side note I have changed the AjaxOptions on the index view that are used for filtering to match what is shown above for paging. I also removed the accepted verbs from the index action so it only responds to get requests. The request for a new set of data based on a filter change is really more of a get operation than a post operation.

Adding Paging Read More »

Partial View with AJAX

This is step two of applying filters to my contact list without refreshing the whole page. I will be using the partial view created in last week’s post.

I ran into a bit of trouble getting ajax working. It seems that starting in MVC 5 the jQuery plugin needed to make this form of ajax work is no longer included by default. In order to fix use NuGet and install jQuery.Unobtrusive.Ajax.nuget-jqueryajax

After the NuGet package is installed add a new bundle (or add to an existing bundle) for the jQuery unobtrusive files to the BundleConfig found in the App_Start folder.

bundles.Add(new ScriptBundle("~/bundles/jqueryunob").Include(
            "~/Scripts/jquery.unobtrusive*"));

If a new bundle was added then make sure to render the new bundle in the _Layout.cshtml file in the Views/Shared folder.

@Scripts.Render("~/bundles/jqueryunob")

The next step was to change the index action of contacts controller. The index action now needs to accept both gets and posts which can be accomplished via the AcceptVerbs attribute. The second change needed in the index action is to return a partial view instead of a view if the request is an ajax request.

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(string city, string search)
{
    var cityList = new List<string>();
    var cityDistinct = from c in db.Contacts
                       orderby c.City
                       select c.City;

    cityList.AddRange(cityDistinct.Distinct());
    ViewBag.city = new SelectList(cityList);

    var contacts = from c in db.Contacts
                   select c;

    if (!string.IsNullOrWhiteSpace(search))
    {
        contacts = contacts.Where(c => c.Name.Contains(search));
    }

    if (!string.IsNullOrWhiteSpace(city))
    {
        contacts = contacts.Where(c => c.City == city);
    }

    if (Request.IsAjaxRequest())
    {
        return PartialView("_ContactList", contacts);
    }

    return View(contacts);
}

Reusing the index action is only one option to implement the needed changes. Another option would be to add another action to the controller that would return the partial view. In this case the  common query code would be moved to a function.

The last set of changes needed are in the index view. Instead of using Html.BeginForm Ajax.BeginForm should be used. The section of the page that will be replaced via the ajax request needs to be moved to a div with an id. In the example below I added a div with the id of contactList. It is important that the div id match the UpdateTargetId in AjaxOptions.

@model IEnumerable<Contacts.Models.Contact>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @using (Ajax.BeginForm("Index",
                           "Contacts",
                           new AjaxOptions
                           {
                               UpdateTargetId = "contactList"
                           }))
    {
        <p>
            City: @Html.DropDownList("city",
                                     ViewBag.city as SelectList,
                                     "All",
                                     new {@class = "city",
                                          onchange = "$(this.form).submit();"})
            Name: @Html.TextBox("Search")
            <input type="submit" value="Filter"/>
        </p>
    }
</p>
<div id="contactList">
    @{
        Html.RenderPartial("_ContactList");
    }
</div>

One thing to make special note of is the that the onchange for the city drop down list has change from “this.form.submit();” to “$(this.form).submit();”. Without this change the request will not come through as an ajax request and the full page will refresh instead of just the contact list section. I wasted a lot of time trying to track down why a full page request was happening and the issue ended up being the way that the drop down list was submitting the form.

Partial View with AJAX Read More »