Thursday, June 30, 2016

VS Item Template for ASP.NET Identity 2.0

ASP.NET Identity does many cool things; a lot more than the old Membership Provider did. I did a project lately that needed to do what the Membership Provider did, Users and Roles. It turns out that the ASP.NET Identity supports Membership, but it is poorly documented.

I looked high and low on the Internet for good examples of ASP.NET Identity doing simple Membership without any extra fluff (my client didn’t want any of it), but did not find any! Since I could not find a good any, I decided to make one and put it on GitHub.

I also built a Visual Studio Item Template that will add most of what you need add and edit roles and users.

The Template

I released my template on my Github account here. It only works with ASP.NET MVC projects created in Visual Studio 2015. It is too stupid to validate that you are using To use my template:

  1. Download FormsAuth.zip from the latest release.
  2. Copy it to <My Documents>\Visual Studio 2015\Templates\Item Templates\Visual C#
  3. Open Developer Command Prompt for VS2015 as administrator
  4. Run devenv /installvstemplates
  5. Open Visual Studio 2015 (don’t use an already opened copy, the template won’t be there)
  6. Create a new project (you can open an existing project as long as it is an ASP.NET MVC project created in VS 2015 or upgraded to ASP.NET Identity 2, VS 2013 projects won’t work, then skip to step 9)
  7. Choose ASP.NET Web Application, name it and click OK
  8. Select the template MVC
  9. Project => Add New Item (or Ctrl+Shift+A)
  10. On the left, select Visual C# then select Forms Auth Role and User CRUD for MVC Project using ASP.NET Identity (better name?)
  11. Follow the instructions in the read me file.

The things I make you do

I wanted to be safe and not touch any of your code, so I am asking you to do it for me.

Create ApplicationRoleManager

The default Visual Studio ASP.NET MVC project is aware of Users but not Roles. You will need to tell it to care about Roels by adding an ApplicationRoleManager. So go to App_Start > Startup.Auth.cs and change the Startup.ConfigureAuth to look like this:

public partial class Startup
{
  
public void ConfigureAuth(IAppBuilder app)
   {
       app.CreatePerOwinContext(
ApplicationDbContext.Create);
      
// Add this line:
       app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
       app.CreatePerOwinContext<
ApplicationUserManager>(ApplicationUserManager.Create);
       app.CreatePerOwinContext<
ApplicationSignInManager>(ApplicationSignInManager.Create);

Add links to navigate to User and Roles pages

OK, you have Users and Roles and forms to edit Users and Roles; but how do you get to them? If you are using the default ASP.NET MVC layout, make the main menu in _Layout.cshtml look like this:

<div class="navbar-collapse collapse">
   <ul class="nav navbar-nav">
       <li>@Html.ActionLink("Home", "Index", "Home")</li>
       <li>@Html.ActionLink("About", "About", "Home")</li>
       <li>@Html.ActionLink("Contact", "Contact", "Home")</li>

       @if (Request.IsAuthenticated && User.IsInRole("Admin")) {
          
<li>@Html.ActionLink("RolesAdmin", "Index", "RolesAdmin")</li>
           <li>@Html.ActionLink("UsersAdmin", "Index", "UsersAdmin")</li>
       }
  
</ul>
   @Html.Partial("_LoginPartial")
</div>

Create “Seed” User

OK, you have all this wonderful User and Role functionality. The trouble is that you need a user who is in the role “Admin” to add and edit users. I added a special form that will allow you to register one and only one “seed” user who will be a member of “Admin”; if it sees that the role “Admin” already exists, it will send you to an error page. Go to http://yourdomain/seeduser/register and create a your new very first Admin user! After you create your seed user, you can delete SeedUserController and the SeedUser Views (files in /Views/SeedUsers).

Other things to do

If you don’t want to expose any of your site to the outside, make all controllers require authorization with the [Authorize] attribute.

Delete Register page and routes (Including my Register Seed User). In the AccountController, delete (or comment out) both Register methods.

Sunday, May 15, 2016

Notes on Roles with ASP.NET Identity on MVC

How do you handle authentication and authorization (or “security”) on a small scale ASP.NET MVC site? The other day I talked to someone who was experiencing problems with setting up security. He set up a MVC project in Visual Studio and couldn’t get it do what he wanted it to do.

Membership Provider

Back in the day there was the Membership Provider, which was easy to use but isn’t hardened enough for these modern times. But was cool, you could set up users and roles with the ASP.NET Web Configuration Tool, you could control access to Controller methods with the Authorize attribute, so if I wanted Admins to access AdminOnly, I could do this:

        [Authorize(Roles = "Admin")]
        public ActionResult AdminOnly()
        {
            return View();
        }

The guy talked to above probably wanted something that behaves like the Membership Provider.

ASP.NET Identity

The Membership Provider has been replaced by ASP.NET Identity, which supports OAuth, Two-factor authentication and other coolness. My problem: there isn’t any obvious support for roles. All of the web examples deal with the new cool (send email to confirm, login using Facebook, etc.)

I created a MVC site on Visual Studio 2015 Community and poking around ASP.NET Identity, I noticed that many of the parts that support roles

AspNetRoles & AspNetUserRoles Tables

I created a new row in AspNetRoles named “Admin” (id = 1) and added a record in AspNetUserRoles to like 1 of my users in AspNetUsers to the role “Admin”.

Decorate Controller method with proper security

I added this method to my new AccessController (I don’t use ActionResult because I’m basically lazy.):

        [Authorize(Roles = "Admin")]
        public string AdminOnly()
        {
            // I don?t use ActionResult because I?m basically lazy. 
            //Otherwise I?d have to create a View.
            return "Welcome, you are allowed here because you are an Admin!";
        } 

1. Without logging on I go to http://localhost:58625/Access/AdminOnly and I get the Login page. Good.

2. Logged in as an administrator and I get to the page. Good.

3. Logged in as a non-administrator and I get the Login page. Weird.

Redirecting to Unauthorized page

OK, you don’t want to go to the Login page when you are logged in and are going to places where you don’t belong. ASP.NET Identity appears to redirect to Login whenever you go to somewhere you don’t belong. It makes the site feel incompetent. So I changed the Login() method in AccountController to:

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Unauthorized", "Account");
            }
            ViewBag.ReturnUrl = returnUrl;
            return View();
        } 

And added

        [AllowAnonymous]
        public ActionResult Unauthorized()
        {
            return View();
        } 

And added the appropriate view.

What about administering my users?

Right now I’m doing it in SQL Server. I’m looking into alternatives. More about that later.

Tuesday, March 22, 2016

Future: Audio Games with Amazon Alexa (or Siri)

The other day I attended an AWS user group where a Solutions Architect for Alexa Voice Service spoke about developing for Alexa. She showed off her Amazon Echo and a couple of skills that she had written for Alexa and urged us all to write our own skills with various AWS services.

I’m not a cloud expert, so much of the details went straight over my head.

She also talked about how voice UI and Alexa are new and will end up everywhere, even cars. We could build an Alexa client on a Raspberry Pi today!

Eliza

Could Alexa run Eliza? When I was in college I learned about Eliza, a program that can respond as a Rogerian psychotherapist (that target was chosen because the natural language processing could be really lame and it would still seam real). After college I bought a 286 computer and found a GWBasic version of Eliza. I played Eliza more like a game, sometimes her responses would make me laugh until it hurts!

The thing that made Eliza so much fun wasn’t the quality of the Natural Language Processing. She could change me to you and you to me and spit the sentence right back to you, track if she had “heard” certain references to your parents and “say” profound things like “I understand”.

I image that the text processing to be wired up as “YOU” and speech synthesis wired to “ELIZA”. I used an online version of Eliza.

Interactive Fiction

Back in the ancient times, in some computer games, you would type commands and the computer would present you with paragraphs of text describing where you are. Why can’t Alexa read the paragraphs to me? I looked around the internet and found a place where I can play Zork online.


Wow! How exciting. Unlike Eliza, Zork has a very limited vocabulary. Looking at the command list I thought I found a way out:


Anyway I was able to wonder around as a ghost. These games where great for the time, a time when 64KB was a huge machine.

Dungeons & Dragons’ Dungeon Master

Eliza is too stupid and classic interactive fiction commands are too primitive. I think the D&D Dungeon Master is a good character for Alixa (or Siri, or Cortana) to play. I’ve listened to Nerd Poker, it is one of many podcasts where people play D&D, they are audio only, so we, as the audience, experience the game without maps.

YOU: Alexa, Dungeon Master
COMPUTER: Welcome to Dungeon Master
YOU: Resume Goldmine
COMPUTER: You are in a timber braced earthen tunnel lit only by the torch you are holding. Up ahead you see a heavy wood door guarded by an orc.
YOU: I take out my sword and approach the door.
COMPUTER: The orc comes toward you displaying his battle axe.
YOU: I attack the orc with my sword

The DM could support higher level commands, In Zork, if I wanted to return to the white house, I would have to the tell the game how to get there (if I can remember). In D&D, I can tell the DM where I want to return to and she would role some dice and tell me if I get back there without any excitement (if she isn’t too uptight); if there is any, she would guide me through any necessary exciting events.

YOU: I would like to return to the Armory
COMPUTER: On the way you meet an orc in the Great Hall.
YOU: I take out my sword.

Future Improvements

Having Alexa’s native voice lead you through a Dungeon would be exciting in the beginning, playing with your ears and all, but after a while, it would get old. What does a future audio games should like? I don’t know, but I would look at other things audio. There is old radio and podcasts, I like the sound of the Black List Table Reads and its Ear Movies could serve a template for the sound design of future audio games.

Cars

With audio games it will be possible to play an audio game while you run down bicycles and mow down pedestrians on your way into the ditch as you conquer dragons and orcs! There is a dark side to new technology!