OAuth/OpenID Support for WebForms, MVC and WebPages

OAuth/OpenID Support for WebForms, MVC and WebPages

Rate This
  • Comments 45

[Update]

Adding relevant links at the bottom of the post

One of the coolest features in Visual Studio 2012 is the ability to login using your Microsoft, Facebook, Twitter or Google account. The project templates showcase a social way of logging in along with the usual way of logging in by creating a local account

This post highlights how you can turn on support for logging through these services in the project  templates. Head over the following video to get a quick glance on this feature http://www.asp.net/vnext/overview/videos/oauth-in-the-default-aspnet-45-templates

Enable OAuth login using Facebook, Twitter

Steps to get keys for Facebook

  • Go to the Facebook developers site (log in if you're not already logged in).
  • Choose the Create New App button, and then follow the prompts to name and create the new application.
  • In the section Select how your app will integrate with Facebook, choose the Website section.
  • Fill in the Site URL field with the URL of your site (for example, http://www.example.com). The Domain field is optional; you can use this to provide authentication for an entire domain (such as example.com).
    Note   If you are running a site on your local computer with a URL like http://localhost:12345 (where the number is a local port number), you can add this value to the Site URL field for testing your site. However, any time the port number of your local site changes, you will need to update the Site URL field of your application.
  • Choose the Save Changes button.
  • Choose the Apps tab again, and then view the start page for your application.
  • Copy the App ID and App Secret values for your application and paste them into a temporary text file. You will pass these values to the Facebook provider in your website code.
  • Exit the Facebook developer site.

Steps to get keys for Twitter

  • Browse to the Twitter developers site.
  • Choose the Create an App link and then log into the site.
  • On the Create an Application form, fill in the Name and Description fields.
  • In the WebSite field, enter the URL of your site (for example, http://www.example.com).
    Note   If you're testing your site locally (using a URL like http://localhost:12345), Twitter might not accept the URL. However, you might be able to use the local loopback IP address (for example http://127.0.0.1:12345). This simplifies the process of testing your application locally. However, every time the port number of your local site changes, you'll need to update the WebSite field of your application.
  • In the Callback URL field, enter a URL for the page in your website that you want users to return to after logging into Twitter. For example, to send users to the home page of the Starter Site (which will recognize their logged-in status), enter the same URL that you entered in the WebSite field.
  • Accept the terms and choose the Create your Twitter application button.
  • On the My Applications landing page, choose the application you created.
  • On the Details tab, scroll to the bottom and choose the Create My Access Token button.
  • On the Details tab, copy the Consumer Key and Consumer Secret values for your application and paste them into a temporary text file. You'll pass these values to the Twitter provider in your website code.
  • Exit the Twitter site.

Steps to enable OAuth support in WebForms

    • Create a new ASP.NET WebForms Application
    • Goto App_Start\AuthConfig.cs and uncomment the following lines of code
OpenAuth.AuthenticationClients.AddTwitter(
                 consumerKey: "your Twitter consumer key",
                 consumerSecret: "your Twitter consumer secret");
 
            OpenAuth.AuthenticationClients.AddFacebook(
                 appId: "your Facebook app id",
                 appSecret: "your Facebook app secret");

Steps to enable OAuth support in MVC

    • Create a new ASP.NET MVC Internet Application
    • Goto App_Start\AuthConfig.cs and uncomment the following lines of code
//OAuthWebSecurity.RegisterTwitterClient(
            // consumerKey: "",
            // consumerSecret: "");
 
            //OAuthWebSecurity.RegisterFacebookClient(
            // appId: "",
            //    appSecret: "");

Steps to enable OAuth support in WebPages

    • Create a new ASP.NET WebSite(Razor2)
    • Goto _AppStart.cshtml and uncomment the following lines of code
//OAuthWebSecurity.RegisterTwitterClient(
            // consumerKey: "",
            // consumerSecret: "");
 
            //OAuthWebSecurity.RegisterFacebookClient(
            // appId: "",
            //    appSecret: "");

OpenID services such as Google

Steps to enable OpenID support in WebForms

  • Create a new ASP.NET WebForms Application
  • Goto App_Start\AuthConfig.cs and uncomment the following lines of code
OpenAuth.AuthenticationClients.AddGoogle();

 

Steps to enable OpenID support in MVC

  • Create a new ASP.NET MVC Internet Application
  • Goto App_Start\AuthConfig.cs and uncomment the following lines of code

OAuthWebSecurity.RegisterGoogleClient();

Steps to enable OpenID support in WebPages

  • Create a new ASP.NET WebSite(Razor2)
  • Goto _AppStart.cshtml and uncomment the following lines of code

OAuthWebSecurity.RegisterGoogleClient();

Links to relevant posts

http://blogs.msdn.com/b/webdev/archive/2012/08/22/extra-information-from-oauth-openid-provider.aspx

http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/23/plugging-custom-oauth-openid-providers.aspx

http://blogs.msdn.com/b/webdev/archive/2012/08/24/customizing-the-login-ui-when-using-oauth-openid.aspx

http://blogs.msdn.com/b/webdev/archive/2012/09/12/integrate-openauth-openid-with-your-existing-asp-net-application-using-universal-providers.aspx

http://blogs.msdn.com/b/webdev/archive/2012/09/19/configuring-your-asp-net-application-for-microsoft-oauth-account.aspx

http://www.asp.net/mvc/overview/getting-started/using-oauth-providers-with-mvc 

Happy Logging in a social way!!!

Leave a Comment
  • Please add 6 and 8 and type the answer here:
  • Post
  • Is there a way to use this and also Authorize the user? For example, if I want the ability to tweet on behalf of a user I have to have an access token and access secret for that user, but this just handles the authentication side.

  • when you authenticate via twitter you do get the auth token back and you can use it to authorize.

    blogs.msdn.com/.../extra-information-from-oauth-openid-provider.aspx

    shows how you get the token and then you can do what you want

  • My site works on http://localhost:12345 but shows the "Bad Request - Invalid Hostname" error when using the local loopback IP address http://127.0.0.1:12345

    Is there anything I need to config to make it work?

    Many thanks

  • Hi everyone.

    I want to get microsoft's secret key and id.

    Can anybody tell me that how to get microsoft's secret key and id.

    plz......................plz.......................plz

  • msdn.microsoft.com/.../live is where you can get keys for a Microsoft account

  • Try this URL to register your app and get your microsoft secret key and Id.

    manage.dev.live.com/AddApplication.aspx

  • I'm also getting this error:

    System.MissingMethodException: Method not found: 'Boolean WebMatrix.WebData.ExtendedMembershipProvider.HasLocalAccount(Int32)'.

      at Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.HasLocalAccount(Int32 userId)

      at PROJECT.Controllers.AccountController.Manage(Nullable`1 message)

      at lambda_method(Closure , ControllerBase , Object[] )

      at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)

      at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)

      at Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionMethod_callback(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)

      at Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget()

      at Castle.DynamicProxy.AbstractInvocation.Proceed()

      at Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation)

      at Castle.DynamicProxy.AbstractInvocation.Proceed()

      at Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()

      at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)

      at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)

      at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)

      at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult)

      at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)

      at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

      at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()

      at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)

      at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)

      at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)

      at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

      at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

      at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

  • Hello there! I must tell you the blog post is really good. It is very informative. I want to mention one thing that I like the way you write the post to the point. I really appreciate and keep writing!

  • @Eonasdan, will it possible for you to share your sample app so that we can debug what the problem is? you can upload it somewhere on skydrive and send me a link via twitter (@rustd)

  • We're starting a new ASP.NET MVC 4 Internet project using Visual Studio 2012.  When we create a new project, all the OAuth/OpenID stuff is included in the project template.  We will not be using OAuth/OpenID and thus do not need it in our project.

    How can all the OAuth/OpenID stuff be removed from the project so that this Internet project uses normal forms authentication?

  • @YoYoMa there is no easy way to remove all the OAuth integration. You can start off by creating a basic template and add parts of the authentication that you want

  • This is intriguing but I don't understand how to transition from a successful auth to using the validated user's credentials to make subsequent REST calls against one of the services. Do you have examples that would show this next step too?

  • I can't pass extra parametert to facebook as scope=email. You you have some solution???

  • Im trying to get the email from a Microsoft Account, but i dont know how to do that, could you please help me?

    I get the userName and im not sure if im getting the userId, but no clues about user email.

  • I am getting this error  on setting localhost url .

    My OAuth settings Client id for web application

    REDIRECT URIS  http://localhost:51763/oauth2callback

    JAVASCRIPT ORIGINS http://localhost:51763/

    Errorr "Error: redirect_uri_mismatch

    The redirect URI in the request: http://localhost:51763/signin-google did not match a registered redirect URI"

Page 3 of 3 (45 items) 123