A Simple ASP.NET vNext MVC Application without Visual Studio 2014 Part 2 (Cookie Authentication)

In the previous post, I covered the steps to get going with a simple ASP.NET MVC application with ASP.NET vNext. This post adds cookie-based authentication to it.

ASP.NET vNext cookie authentication middleware is very similar to the OWIN/Katana middleware. We need three new packages and add the same to the project.json file like below.

{
 "dependencies": {
      "Microsoft.AspNet.Hosting": "1.0.0-*",
      "Microsoft.AspNet.Mvc": "6.0.0-*",
      "Microsoft.AspNet.Server.WebListener": "1.0.0-*",
      "Microsoft.AspNet.Security": "1.0.0-*",
      "Microsoft.AspNet.Security.Cookies": "1.0.0-*",
      "Microsoft.Framework.OptionsModel": "1.0.0-*"
  },
  "commands": {
  "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
  },
 "frameworks": {
  "aspnet50": { }
 }
}

Then, do a kpm restore. Next, we will plug in the middleware by modifying the Startup.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.DependencyInjection;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Security.Cookies;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseServices(services =>
        {
            services.AddTransient<IDataSource, SillyDataSource>();
            services.AddMvc();
        });

        // Added now
        var options = new CookieAuthenticationOptions();
        options.LoginPath = new PathString("/Home/Login");
        app.UseCookieAuthentication(options);
        // End addition

        app.UseMvc(routes =>
        {
            // Same as before
        });
    }
}

Now, we need to apply the Authorize filter to protect resources. When there is a unauthorized request to such resource, filter returns 401 and the cookie middleware redirects to /Home/Login. So, we need an action method to handle the redirect. The changed controller class is below. The login mechanism is just for illustration. As long as there is a user name entered in the login form, identity is established with that name.

using Microsoft.AspNet.Mvc;
using System;
using System.Security.Claims;
using Microsoft.AspNet.Security.Cookies;

[Authorize]
public class HomeController : Controller
{
    private readonly IDataSource dataSource;

    public HomeController(IDataSource ds)
    {
        this.dataSource = ds;
    }

    public IActionResult Index()
    {
        ViewBag.Message = this.dataSource
                           .GetMessage(User.Identity.Name);
        return View();
    }

    [AllowAnonymous]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public IActionResult Login(string name)
    {
        // This is just for illustration.
        // Just try to pretend authentication
        // happens here!
        if(!String.IsNullOrWhiteSpace(name))
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, name)
            };
            var identity = new ClaimsIdentity(claims, 
                CookieAuthenticationDefaults.AuthenticationType);
            Context.Response.SignIn(identity);

            return Redirect("~/");
        }

        return View();
    }
}

The new login view is like so.

@{
    Layout = "/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    @Html.TextBox("Name")
    <input type="submit" name="go" />
}

With that, cookie authentication is enabled. If you go to the home page, you will get redirected to /Home/Login where you can enter any name there and based on that, identity is established.

BTW… If you have difficulty getting the Microsoft.AspNet.Security.Cookies or any other related packages, make sure you create a text file in the HelloWorld folder with the name of NuGet.Config and copy paste the XML below.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AspNetVNext" value="https://www.myget.org/F/aspnetmaster/api/v2/" />
    <add key="NuGet.org" value="https://nuget.org/api/v2/" />
  </packageSources>
</configuration>

This ensures the right packages are pulled when you do a kpm restore. However, this file will not be used unless one of the following is true. See this.

HelloWorld folder contains

  1. A .sln file
  2. A global.json
  3. A .git folder
  4. A packages folder

So, before you do a restore, create a folder “.git” under HelloWorld using mkdir .git.

Advertisements

2 thoughts on “A Simple ASP.NET vNext MVC Application without Visual Studio 2014 Part 2 (Cookie Authentication)

  1. Thank you for great articles!

    While tried reproduce your sample got following error at Startup.cs where you are saying to app that you are going to use cookie authentication:

    Startup.cs(19,37): error CS1503: Argument 2: cannot convert from ‘Microsoft.AspNet.Security.Cookies.CookieAuthenticationOptions’ to ‘System.Action’

    It seems that method signature changes, so for thous who are getting same error here is fix:

    app.UseCookieAuthentication(options => {
    options.LoginPath = new PathString(“/Home/Login”);
    });

    Taken from: https://github.com/aspnet/Security/tree/dev/samples

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s