Scott Hanselman

Integrating Mozilla Persona with ASP.NET

January 24, '13 Comments [13] Posted in ASP.NET | ASP.NET MVC | ASP.NET Web API | Open Source
Sponsored By

imageASP.NET and Web Tools 2012.2 is coming soon, but one of the features of ASP.NET that you can use TODAY is support for Google, Twitter, Microsoft and Facebook logins out of the box with ASP.NET templates. I show how OAuth in ASP.NET works in this 5 minute video. We are also continuing to look at ways to make membership easier in coming versions of ASP.NET like including things like this out of the box.

Mozilla has a new identity system called Mozilla Persona that uses browserid technology to let users log in to your site without creating a custom login or username.

I wanted to see how Persona would work in ASP.NET and hacked up a prototype (with some sanity checking from my buddy Hao Kung). There's some comments and some TODOs, but it's a decent proof of concept.

First, I read the Mozilla Persona Developer docs and got their fancy button CSS, then added it all to the ExternalLoginsListPartial view.

The Magic Persona button is very blue

The ProviderName check is there just because all the buttons look the same except the Persona one. A better way, perhaps, would be partial views for each button, or a custom helper.

@foreach (AuthenticationClientData p in Model)
{
if(p.AuthenticationClient.ProviderName == "Persona") //ya, ya, I know.
{
if (!Request.IsAuthenticated) {
<p><a href="#" class="persona-button" id="personasignin"><span>Sign in with your Email</span></a></p>
}
<!-- The CSS for this is in persona-buttons.css and is bundled in in BundleConfig.cs -->
}else{
<button type="submit" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in using your @p.DisplayName account">@p.DisplayName</button>
}
}

After the login dialog, an AJAX call to do the login locally posts data to my new PersonaController. except it doesn't POST its assert as JSON, but rather as a simple (standard) POST value. That is, just "assertion: longvalue."

function onAssertion(assertion) {
if (assertion) {
$.ajax({ /* <-- This example uses jQuery, but you can use whatever you'd like */
type: 'POST',
url: '/api/persona/login', // This is a URL on your website.
data: { assertion: assertion, },
success: function (res, status, xhr) { window.location.reload(); },
error: function (res, status, xhr) { alert("login failure" + res); }
});
}
else {
alert('Error while performing Browser ID authentication!');
}
}

ASP.NET Web API doesn't grab simple POSTs cleanly by default, preferring more formal payloads. No worries, Rick Strahl solved this problem with this clever SimplePostVariableParameterBinding attribute which allows me to just have string assertion in my method.

Armed with this useful attribute (thanks Rick!) my PersonaController login is then basically:

  • Get the assertion we were given from Persona on the client side
  • Load up a payload with that assertion so we can POST it back to Persona from the Server Side.
  • Cool? We're in, make a local UserProfile if we need to, otherwise use the existing one.
  • Set the FormsAuth cookie, we're good.

Here is the work:

[SimplePostVariableParameterBinding]
public class PersonaController : ApiController
{
// POST api/persona
[HttpPost][ActionName("login")]
public async Task<HttpResponseMessage> Login(string assertion) {
if (assertion == null) {
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var cookies = Request.Headers.GetCookies();
string token = cookies[0]["__RequestVerificationToken"].Value;
//TODO What is the right thing to do with this?

using (var client = new HttpClient()) {
var content = new FormUrlEncodedContent(
new Dictionary<string, string> {
{ "assertion", assertion },
{ "audience", HttpContext.Current.Request.Url.Host }
//TODO: Can I get this without digging in HttpContext.Current?
}
);
var result = await client.PostAsync("https://verifier.login.persona.org/verify", content);
var stringresult = await result.Content.ReadAsStringAsync();
dynamic jsonresult = JsonConvert.DeserializeObject<dynamic>(stringresult);
if (jsonresult.status == "okay") {
string email = jsonresult.email;

string userName = null;
if (User.Identity.IsAuthenticated) {
userName = User.Identity.Name;
}
else {
userName = OAuthWebSecurity.GetUserName("Persona", email);
if (userName == null) {
userName = email; // TODO: prompt for custom user name?
using (UsersContext db = new UsersContext()) {
//TODO: Should likely be ToLowerInvariant
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == userName.ToLower());
// Check if user already exists
if (user == null) {
// Insert name into the profile table
db.UserProfiles.Add(new UserProfile { UserName = userName });
db.SaveChanges();
}
}
}
}

OAuthWebSecurity.CreateOrUpdateAccount("Persona", email, userName);

FormsAuthentication.SetAuthCookie(email, false);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}

[HttpPost][ActionName("logout")]
public void Logout() {
WebSecurity.Logout();
}
}

You click Sign in and get the Persona login dialog:

Animation of the Persona login

At this point, you're logged into the site with a real UserProfile, and things with ASP.NET Membership work as always. You can add more external logins (Twitter, Google, etc) or even add a local login after the fact.

You are logged in!

As I said, this isn't ready to go, but feel free to poke around, do pull requests, fork it, or comment on how my code sucks (in a kind and constructive way, because that's how we do things here.)

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

You are not your code.

January 24, '13 Comments [60] Posted in Musings
Sponsored By

Photo by Ed Yourdon used under CC http://flic.kr/p/55YkTjI'm a lousy programmer. However, I am less lousy than I was last year, and significantly less lousy than I was 20 years ago. Even still, there's a lot of crap on my GitHub and Bitbucket repos - but I'm totally OK with it.

I am not my code.

Yes, it's a reflection of me, but just as I am not my 8th grade English paper or my college entrance scores, I am not the code I wrote last year. Feel free to tear it apart. I will be better this year.

Your code does affect your reputation, truly. It is possible that you are a bad programmer. You'll never know until someone better sees it. Sharing your code may find you a mentor, or get a teacher's critical eye and help fixing it. Pull requests can't happen until you've shared your code.

I'll steal clone David Copeland's summary of this week's "social coding scandal."

So, someone shared some code on Github and some classic developer snark rolled in. And then there were some apologies about it.

The irony is, of course, that the code in question was actually rather useful, didn't require idiomatic command line knowledge, and, most importantly solved someone's problem.

Don't let any of internet drama stop you from writing on your blog or from contributing to open source. In fact, I would encourage you to release some source code right now. Go find some, I'll wait.

Have a code garage sale. One person's junk is another person's treasure.

"I can't believe I found code that does exactly what I needed."

"Wow, I learned a lot from that algorithm."

Feel free to share some of your lousy code in the comments, and we all promise not to judge you. Feel free also to share some awesome code if that makes you happy, as long as you share.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Cancer

January 22, '13 Comments [273] Posted in Musings
Sponsored By

What would your list look like on the day of your second cancer surgery?

Cancer. My wife has, or hopefully by now, had Cancer.

See that To Do List in the picture at the right there? That's how awesome my wife is. This is her list for the day of the surgery that would remove organs and important stuff and lay her up for many weeks.

Pack.
Cut toenails.
Paint toenails.
Clean bathrooms.

God forbid one should enter a major surgery with a messy bathroom or unkempt toenails. This is just how my wife rolls and I think she's awesome.

It's been a crazy several months since this Cancer was picked up by the lab during a routine check up. This was then followed by a PET scan, a surgical procedure and then another more major surgery.

School was starting soon for the kids, my wife is embarking on a new career and had classes all week. I needed to prep and attend the BUILD conference, be in the keynote, host 4 hours of live TV, plus deliver two talks. Just to make the point - life was happening when Cancer happened.

Let me tell you, Cancer is damned inconvenient when you're trying to live your life. It blindsided us completely but we continued to manage all our commitments while our little boys played and danced even though "mommy had a tummy-ache."

As of today there will be checkups every 3 months for some years. We think it's all handled and gone but now we wait. We wait five years, in fact, because that's when Cancer People graduate and get the "cancer-free" label.

I asked my wife when we could get her an "I beat Cancer" T-Shirt. She said that it's a little early. I may just buy a "She beat Cancer ->" shirt for myself and stand next to her.

Negative for Tumor - pathology

They took so much out of her it hurts me to think about it. Weeks later, dressed to the nines for the family Christmas party but with a hidden catheter bag on her leg, I've never been prouder of her strength and patience. Two months into various side effects while she is at a low point I am reminded she is only human, and as fragile as I. We're both a mess but we're together.

She's handling this whole thing with grace and aplomb and I'm so proud of her. If I could have taken it away and been the one that had Cancer (I always see the C as a Capital C when I say Cancer in my head) I would have.

The boys don't know anything about this, but perhaps 5 years from now we'll tell them that Mommy beat Cancer when they were younger. Even better if in 5 years medicine will find a way to keep Cancer from needing a Capital C.

Why am I telling you this, Dear Reader? Because we found this on a regular checkup. Please, get whatever regular screenings are appropriate for your age and gender. If you haven't been to the doctor in years, go today. These things are easier to beat when they are found early.

Let's hope that 2013 is an easier year.

UPDATE: A number of kind people have asked about funds and bills. We are fortunate to have insurance and will be able to pay our bills. If you want to help, please read Troy Howell's family's story and donate. He will die soon and they are raising money to cover the funeral costs and medical bills. http://www.troyhowellcancerfund.com

UPDATE #2: My wife and I have taken 6 months of our personal audio Cancer Diary and turned it into an episode of This Developer's Life. We hope you enjoy it.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Unlocking Windows 8 "God Mode" - A Useful Trick but also Mysterious Nonsense

January 18, '13 Comments [42] Posted in Win8
Sponsored By

Everyone likes the idea of a cheat mode, or "God Mode." Many years ago - I think around 1993 - Doom introduced the idea of switching a player into God Mode within the game by typing IDDQD. You'd then be invincible and get to feel like you'd discovered an exciting secret "easter egg" in the game. How exciting the the developers hid this for us to find!

You may have heard of a "God Mode" hidden in the depths of Windows 8 (or 7 for that matter). The idea is that you make a folder somewhere, I like using my desktop, and name the folder "GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}" and it "unlocks" a bunch of secret functionality.

Let's try.

Make a God Mode Folder for Windows

Now I hit Enter...

God Mode looks a lot like the Control Panel

Hm, the folder icon looks like the Control Panel now, and the long GUID (Globally Unique Identifier) is gone.  Cool.

What's the properties for this folder say? Right Click, Properties. There's the Type with the GUID. It's not just a File Folder, it's a File Folder with some metadata associated..

God Mode is a folder with a GUID at the end

Where is this GUID in the Registry? Let's run Regedit.exe and Find it.

God Mode in the registry is a GUID pointing to the Control Panel

Ah, it's the All Tasks view of the Control Panel. By naming this folder this way, its view is now the Control Panel with All Tasks shown.

But 'GodMode?' That is a little dodgy as a name, right? That might offend. Is it needed? Let me rename it to MagicPants.

You can name the GodMode folder whatever you want

Does it still work? Sure. I can call it whatever I need.

I renamed my folder "Magic Pants"

Is there a reason to have this "All Tasks" folder? No. It's just a view on a list of control panel tasks you already have.

See there where it says "add clocks for different time zones?" What if I just press the Start Button and type "add clocks" and click on Settings?

You can already search settings for ALL these Control Panel tasks

The Control Panel tasks are searched from the Start Screen's settings already. They always have been, even in Windows 7.

If you like the idea of an "All Tasks" or "God Mode" folder, be happy and make yourself one on your desktop. If not, know that ALL those features are already there. Just press the Windows button, type something, and hit settings. If you're a hotkey person, you can press Windows Key + W and access any of these 265 (and growing) helpers to customize your system.

Some cool examples, search for "RAM"

Search for RAM

or "Fonts"

Search for Fonts

or "Mouse"

Search for Mouse

Either way, enjoy the God Mode that your computer already has, or feel free to customize your machine to your heart's content.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

The Missing Windows 8 Instructional Video

January 12, '13 Comments [68] Posted in Screencasts | Win8
Sponsored By

A few months ago while sitting at a Burger King (yes, I know) I recorded a video on "How to use Windows 8 in 3 minutes" and threw it up on YouTube. It's been viewed nearly a half million times. Eek. It's got poor audio, and it's WAY too fast. I did it on a goof. However, people keep showing it to family and friends.

A man emailed me after sending it to his elderly uncle and let's just say that the uncle wasn't impressed with the speed of the video either. It's great for geeks but not for normal people.

So tonight I took a few hours and did a new video that I'm VERY happy with and I hope you enjoy it. It's clean, clear, and only 25 minutes long and it explains, I believe, Windows 8 and its changes for anyone with basic Windows experience.

I hope you like it and you share it with family and friends. Also check out the related posts at the bottom.

The Missing Windows 8 Instructional Video - 25 minutes

Related Posts you may enjoy

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.