Azure DevOps, Scrum, & .NET Software Leadership and Consulting Services

Free course! Predicting the Future, Estimating, and Running Your Projects with Flow Metrics

Walkthrough: ASP.NET MVC Identity with Microsoft Account Authentication


UPDATED (May 16, 2016)If you’re looking for how to do this with ASP.NET Core, here’s the ASP.NET Core 1.0 version.

UPDATED (June 13, 2014)With the latest version of the ASP.NET Identity / OWIN libraries and code, the Redirect URL value that you’ll use in Step #8 should now be “http://www.mysampleapp.com/signin-microsoft”.  If you’re getting an error that says Invalid redirect_uri value and you’ve just recently created the project, this is probably what’s going wrong.

I’ve been playing with ASP.NET and social identity providers lately.  The samples are all focused on using either Facebook authentication or Google authentication and the documentation for how to use a Microsoft Account is pretty thin.  When I started working on it, it was unclear where I needed to go and what I needed to do to make it work on my development machine.  The error messages were vague, too.

Eventually, I got it working and here’s the walkthrough on getting it working with Visual Studio 2013.

Step #1: Create a Project

Open Visual Studio 2013.  Click New Project.  Choose ASP.NET Web Application as the project type.  Give it a name for the project and the solution.  Click OK.

image

 

Step #2: Create the MVC Project

You’ll see a dialog that says “New ASP.NET Project”.  Choose MVC.  Make sure that the Authentication value is set to Individual User Accounts.  Click OK.

image

 

Step #3: Open Startup.Auth.cs

The settings for the user authentication providers for your ASP.NET MVC project are stored and specified in the Startup.Auth.cs file.  In Solution Explorer, go to the ASP MVC project and expand the App_Start folder.  Double-click the Startup.Auth.cs file.

 

SNAGHTML3454a216

 

Step #4: Enable Microsoft Account Authentication

Startup.Auth.cs should now be open.  Locate the line that says app.UseMicrosoftAccountAuthentication.  That line is commented out by default.  Uncomment that line so that it looks like the screenshot below.

SNAGHTML3457cabd

Step #5: Create a Client ID and Client Secret for Microsoft Authentication

At the moment, the clientId and clientSecret parameter values are blank.  You need to get these values from the Live Connect Developer Center.  You can get it it by going to this link: http://go.microsoft.com/fwlink/?LinkID=144070  Log in to this site using your Microsoft Account (aka your Live ID).  You should eventually end up at the My Applications page (https://account.live.com/developers/applications/index).  Click on the Create application link to start the process of creating an application.

SNAGHTML345ce060

Step #6: Create the Application on Live Connect Developer Center

Add a value for Application name and click the I accept button.

SNAGHTML345ee047

Step #7: Save the basic settings

You should now see a screen that looks like the screenshot below.  Optionally, you can add an application logo, terms of service url, and privacy url.  Populate these values if you want to.  Click the Save button.

SNAGHTML3460733b

 

Step #8: Populate the API Settings

Click the API Settings link in the left column of the screen.  You should now be on a screen that looks similar to the screenshot below.  You need to populate the Redirect URLs textbox.  When a user logs in to your app successfully, the Microsoft Account service will redirect them back into your application.  The Redirect URL value is URL in your app where they’ll be sent.  In this sample, we’re going to say that our domain name is www.mysampleapp.com.  Don’t worry.  You don’t have to actually register this domain.  I’ll walk you through how to make this work all entirely on your development machine later in this post.  Set the Redirect URLs text box to http://www.mysampleapp.com/Account/ExternalLoginCallback and click the Save button.

UPDATE (June 13, 2014) — With the latest version of the code, the Redirect URLs value has changed.  If you’re getting an error when you run the app that says invalid redirect_uri, then you should change this value to http://www.mysampleapp.com/signin-microsoft.

SNAGHTML34646df8

 

Step #9: Activate & Copy App Settings

In the left column, click the App Settings link.  You should now see a screen that looks similar to the one below.  This screen shows you the Client ID and Client Secret values that you’ll be adding into your ASP.NET MVC application’s Startup.Auth.cs file.  Click the Activate button.  If you’re prompted, to activate new client secret, click OK.

SNAGHTML346b9f37

Step #10: Add Client ID and Client Secret values to Startup.Auth.cs

Leave the browser window open and go back to the Startup.Auth.cs file in Visual Studio 2013.  Plug the clientId and clientSecret values from the browser into the call to UseMicrosoftAccountAuthentication in Startup.Auth.cs.

SNAGHTML346ff032

Step #11: Make it work on your development machine

At the moment, if you run this, it’s going to fail because the redirect url points to a bogus domain name that doesn’t DNS resolve to your development machine’s address.  You can fix this by editing the Windows hosts file.  This file overrides the DNS resolution for addresses that you specify.  The file is located in c:windowssystem32driversetc.  (NOTE: there is no file extension on the hosts file.)

Open a Command Prompt window as an Administrator.  Type cd windowssystem32driversetc and press <enter>.

Next, open the hosts file in notepad.  Type notepad hosts and then press <enter>.

SNAGHTML349d8718

Step #12: Using notepad, add an entry for the domain name

Notepad.exe should now be open and it should look similar to the file below.  Go to a blank line.  Type 127.0.0.1 www.mysampleapp.com and save the file.  You can now exit notepad.

SNAGHTML349f4d13

Step #13: Verify hosts file changes for www.mysampleapp.com

You can verify that your changes to the hosts file worked by doing a ping test.  Type ping www.mysampleapp.com and press <enter>.

You should see ping output that looks similar to the screenshot below.

SNAGHTML34b75da8

Step #14: Re-open Visual Studio as an Administrator

By default, an ASP.NET MVC project in Visual Studio opens for debugging purposes in IIS Express.  Out of the box, IIS Express does not support custom domain names and, because of this, I decided to run/debug this sample using the full version of IIS.  In order to configure the settings for this, Visual Studio needs to be run as an Administrator so that it can administer IIS’s settings.

Save any changes to the solution in Visual Studio.  Close Visual Studio.  Re-run Visual Studio as an Administrator.

Here are the steps if your Visual Studio app icon is pinned to the task bar.  Right-click the Visual Studio 2013 icon.  When the menu comes up, right click the small Visual Studio 2013 icon and choose Run as administrator from the context menu.

SNAGHTML34bf449b

 

When Visual Studio 2013 is open, re-open the solution (*.sln).

 

Step #15: Change the settings for the ASP.NET MVC project

In Solution Explorer, right-click the ASP.NET project and choose Properties from the context menu.

SNAGHTML34c1358e

From the left column, choose Web.  Under the Servers section, change the drop down list to say Local IIS.  Click the Create Virtual Directory button to finish configuring IIS.  If prompted

SNAGHTML34c44d4e

The IIS site has now been created.

Click the Save button in Visual Studio to save the changes to the project file.  You’re going to be prompted to modify your database connection strings.  Click Yes.

image

 

Step #15: Verify your database connection settings in Web.config

Chances are high that your database connection string is now wrong.  Open the Web.config file for the ASP.NET project.  Locate the connection string for DefaultConnection.  Verify that this database connection string points to a valid database.

 

Step #16: Run the app

Start debugging the app using Visual Studio.

SNAGHTML34cbd0f3

When the browser comes up, change the URL field to be the same URL but with www.mysampleapp.com instead of localhost.

SNAGHTML34cdd29f

In the upper-right corner of the window, there’s a link that says Log in.  Click the Log in link.

 

SNAGHTML34cf012c

Step #17: Log into the app

You should now be on the login page.  There should be a section of the page that says Use another service to log in and there should be a button that says Microsoft.  Click the Microsoft button.

SNAGHTML34d04e3e

You should now see the Microsoft account login screen.  Enter your username and password and click Sign in.

SNAGHTML34d20cd6

You should now see a screen that is asking Let this app access your info.  Click the Yes button.

SNAGHTML34d30511

Step #18: Enjoy

You should now be finished logging in and you should see your user account info in the menu bar.  You’re done!

SNAGHTML34d4edf5

 

I hope this helped!

-Ben

SUBSCRIBE TO THE BLOG


56 responses to “Walkthrough: ASP.NET MVC Identity with Microsoft Account Authentication”

  1. Gregor Avatar
    Gregor

    wow. looks like this only got published yesterday! Awesome tutorial. No clue how I would have figured this out otherwise … Thanks a lot.
    Gregor

    1. Ben Day Avatar

      Hey Gregor–

      Yup. Published it yesterday afternoon. Glad it helped you out!

      -Ben

  2. Gregor Avatar
    Gregor

    wow. looks like this only got published yesterday! Awesome tutorial. No clue how I would have figured this out otherwise … Thanks a lot.
    Gregor

    1. Ben Day Avatar

      Hey Gregor–

      Yup. Published it yesterday afternoon. Glad it helped you out!

      -Ben

  3. Terry McCarthy Avatar
    Terry McCarthy

    awesome. Thanks, Ben, great post!

  4. Terry McCarthy Avatar
    Terry McCarthy

    awesome. Thanks, Ben, great post!

  5. Thao Le Avatar
    Thao Le

    Thanks Ben,

  6. Thao Le Avatar
    Thao Le

    Thanks Ben,

  7. […] found a good walkthrough here on how to setup Microsoft Account Identity, after I’d worked it out myself unfortunately. […]

  8. […] found a good walkthrough here on how to setup Microsoft Account Identity, after I’d worked it out myself unfortunately. […]

  9. Claus Avatar
    Claus

    Perfect job!
    Thanks – you literally saved my day with this awsome post!

  10. Pradeep Avatar
    Pradeep

    Hi Ben Day,
    I tried the scenario what you have mentioned above but still i am getting the same exception from Microsoft.

    We’re unable to complete your request
    Microsoft account is experiencing technical problems. Please try again later.

    and i am getting the following URL

    https://login.live.com/err.srf?lc=1033#error=invalid_request&error_description=The provided value for the input parameter ‘redirect_uri’ is not valid. The expected value is ‘https://login.live.com/oauth20_desktop.srf’ or a URL which matches the redirect URI registered for this client application.&state=rhQUFR1CfmM7WRkKPr304vuRsH0wKf6HG8DMNzMM79eNtiWaD8hkr_fm0t7uwEm3UegdvJ9fZnuEfXecGMZhwnKBTf_EFmjSqZmTYEKnLO5hEJxEzUPJetqej9W1JwcEgtSGEvNspGKFwLp_K8LhQmUmV7pR-bw793ECPTTdUx1k

    1. Ben Day Avatar

      Hi Pradeep —

      I just ran into this problem a few days ago myself and I’ve been meaning to update this post.

      With the latest version of the ASP.NET Identity code, the redirect uri is a different value. So on account.live.com, the redirect url value for your app is now going to be “http://myapp-url/signin-microsoft”.

      -Ben

      1. Pradeep Avatar
        Pradeep

        Thanks a lot Ben…
        Its working fine now.

        Best Regards
        Pradeep

        1. Lucas Avatar
          Lucas

          I can´t make it work on localhost, when I publish the application it is fine, I´ve already changed my hosts file. Any tips?

          1. Ben Day Avatar

            Lucas–

            Just to double-check. After you change the hosts file, you won’t be going to “http://localhost” any longer. It’ll be whatever url value you put into the hosts file.

            What’s the error that you’re getting? The error message is usually embedded in the URL query string.

            -Ben

          2. Lucas Avatar
            Lucas

            The error is the redirect_uri.

            But I guess the problem is with the request headers:

            https://login.live.com/oauth20_authorize.srf?client_id=000000004C122631&scope=wl.basic&response_type=code&redirect_uri=http%3A%2F%2Fboletoonline.azurewebsites.net%2FInforma.BoletoOnline%2Fsignin-microsoft&state=uKCKe1zepIAuqlPnRg2J-sT2-

            It is not pointing to the root domain, it´s appending the folder “Informa.BoletoOnline”… how should I fix that?

      2. Bill Waddy Avatar

        Thanks for your help with this issue Ben.

  11. Alex Jamrozek Avatar
    Alex Jamrozek

    Thanks for this post and the updates. I had to dig in the response header a little more to really dial in the RedirectUrl.
    http://stackoverflow.com/questions/15025218/mvc-oauth-vs2012-template-where-to-enter-the-redirect-uri

  12. […] SDK noch weitere Daten abrufen – aber für die pure Authentifizierung reicht das schon mal. Der Blogpost hier in englisch hat mir bei der Redirect-URL […]

  13. Ben Day Avatar

    Lucas —

    I’d check that you have the right values plugged in at Step #8.

    -Ben

  14. Richard Evans Avatar
    Richard Evans

    Just when I needed it. It is amusing that Microsoft’s documentations explains how to set up Google and Facebook, but not their own service. Thank you.

  15. ekambar Avatar
    ekambar

    hi, I have tried this and have been getting error as HTTP Error 500.19 – Internal Server Error
    Module
    IIS Web Core

    Notification
    BeginRequest

    Handler
    Not yet determined

    Error Code
    0x80070021

    Config Error
    This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=”Deny”), or set explicitly by a location tag with overrideMode=”Deny” or the legacy allowOverride=”false”.

    Config File
    \\?\C:\Users\ekambar\documents\visual studio 2013\Projects\MicrosoftLogin\MicrosoftLogin\web.config

    Any help to resolve this is very much appreciated.

  16. Danister Avatar
    Danister

    Hi ben,
    great post, but im stuck with the invalid redirect url error.
    I tried both the url’s you have mentioned in the post
    “http://myapp-url/signin-microsoft”. and the initial Url.
    Both did not work.

    This is the error url i get directed to

    https://login.live.com/err.srf?lc=1033#error=invalid_request&error_description=The%20provided%20value%20for%20the%20input%20parameter%2

    Any input on this ?

    1. Sarita Avatar
      Sarita

      I have use following link that solution is working for me.

      http://www.oauthforaspnet.com/providers/microsoft/guides/aspnet-mvc5/

  17. leigh007 Avatar
    leigh007

    I know this is real late, but I’m getting the same problem as Danister above.

    Like all things, it would be nice for me to know a bit more about how the different parameters registered for the app at live.com are used.

    In the absence of that, I’m just guessing when things don’t work.

    -thanks
    -e

  18. […] the basic application setup, I’ve used this excellent tutorial: http://www.benday.com/2014/02/25/walkthrough-asp-net-mvc-identity-with-microsoft-account-authenticat&#8230;. I customized using my Microsoft developer portal client ID and secret, and set up the […]

  19. Sherry Avatar
    Sherry

    Hello,

    How do I get the Email address of the user since I just get username right now. Any help?

  20. Hydtechie Avatar
    Hydtechie

    I am able to see the token generated after successful login in live.com but my mvc template is showing LOGIN page only instead of Register .. What am I missing? appreciate your help!

  21. Kamalesh Avatar
    Kamalesh

    This works good. I need to get the PUIDHigh and PUIDLow. How can we get that?

  22. joe Avatar

    Great walkthrough … what software are you using to get the thorn effect on screenshots ?

    1. Ben Day Avatar

      That’s TechSmith’s SnagIt. SnagIt is teh awesome.

  23. Gouri Avatar
    Gouri

    I get error at the Redirect URLs : “You must enter a valid domain that begins with http:// or https:// – query strings are not allowed. Length is limited to 248 characters.

    I have given ” http://www.mysampleapp.com/signin-microsoft” in Redirect URL.

    1. Ben Day Avatar

      Hi Sarita —

      The details of the error are embedded in “error_description” field of that URL. It looks like it’s saying that the redirect url doesn’t match the configuration at Live.com. I’d start looking there.

      -Ben

      1. Sarita Avatar
        Sarita

        Hi Ben Day,
        sorry but i didn’t understand Problem actually,
        Need any other setting for that Redirect URL? Can you tell me what can i do now?
        Please help me.

        1. Jakub Avatar
          Jakub

          Hi Sarita,

          I had the same problem and it looks that redirect url: http://www.mysampleapp.com/signin-microsoft is incorrect.
          Use this link as redirect url and it should be fine: http://www.mysampleapp.com/Account/ExternalLoginCallback

  24. […] Walkthrough ASP.NET MVC Identity with Microsoft Account authentication […]

  25. Andy Schwam Avatar

    Ben,
    Thanks. This is a really good tutorial. In particular, the update that mentions “signin-microsoft” really saved me. I’ve been trying to figure that out for days! Thanks!

    -Andy

    1. Mark Avatar
      Mark

      Thank you Ethan. I’ve been fighting this for days. The Fiddler solution worked for me.

  26. Sam Van Daele Avatar
    Sam Van Daele

    How can I deny acces for certain users

  27. Pavan Avatar

    Can you please share the list of values that you get with token ?

  28. Pavan Avatar

    can you please share the list of values that you get in token and does that include email address in clear text ?

  29. Marcus Nordquist Avatar

    Great job! Would be awesome to see this exact walkthrough but for a ASP.NET Core 1.0 WebAPI.

  30. […] exactly 100% straight-forward.  The documentation is pretty vague.  A couple years ago I wrote a walkthrough guide for setting up Microsoft Account authentication provider for ASP.NET 4.*.  Now that the release of ASP.NET Core 1.0 is just around the corner, I’ve started getting […]

  31. Jitendra Rohira Avatar
    Jitendra Rohira

    what if i don’t want that login button in /Account/login(Visual Studio’s default login Account page)
    i want the login button in a custom Login webpage which i have created.

    my path is /abc/Default and i want that Microsoft sign-in button in Default page.
    i tried changing the login path in Startup.Auth.cs from /account/login to /abc/Default it didn’t work.

    how do i show the login button in /abc/Default page?

    1. Ben Day Avatar

      Jitendra –

      What errors did you get when you changed that path? I’d expect that you could move that pretty easily as long as you make your custom form post back to the correct controller action.

      -Ben

  32. Saeid Avatar
    Saeid

    Thanks Ben for sharing; I am new in .Net programming and need lot of help from experts like you. I am programming as a volunteer for a child care organization. As part of their authentication need, they want my .Net MVC app to work with emplyee’s outlook account. Is there anyway I can do so? Do you have any guide on this topic? I appreciate it.

  33. […] For more information on this and for exact walkthrough on it, check out this and this.   , enter the values for Client Id and Client Secret, select wl.basic and wl.signin, […]

  34. Sailaja Avatar
    Sailaja

    Hi Benday

    Nice article. It was very helpful.

  35. Lorena Avatar
    Lorena

    Hi Ben, have you test the 3.1.0 owin versions with the MicrosoftAccount login? I am having some troubles enabled https for the localhost and always get access_denied

  36. Rohan Raohan Avatar

    If I want to check this email with the local database how can I do that? I mean, when I enter the username and password for MS authentication, it should check whether my username and password is present in local db. If yes, then only it should authenticate. How can I do this?

  37. Rohan Rao Avatar

    Can you tel me exactly what error is giving for access_denied?

  38. mon40 Avatar

    Hello from 2021. This still works. Though I did replace steps 11-13 with a piece of software called ngrok for tunneling

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.