Wednesday, 3 July 2013

Login With Twitter And Yahoo using DotNetOpenAuth Using ASP.NET C#

Login With Twitter And Yahoo using DotNetOpenAuth Using ASP.NET C#

Hello once again,

I am currently working on a social site and found its typical to find login with twitter and yahoo. i have done it using DotNetOpenAuth. i don't want the other developer will waste their precocious time on the R&D for this topic. Hope it will work for you too.

Steps to follow:

1. Create a Empty Website in C#
2. Tools --> Library Package manager --> Package Manager Console
3. Download samples from
3. PM> Install-Package DotNetOpenAuth
4. Now Add Reference of "OAuthConsumer.dll", "OAuthConsumer.dll"  and "DotNetOpenAuth.ApplicationBlock.dll"  from the samples
5. The HTML file will be like the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty"

    TagPrefix="rp" %>

<%@ Register Assembly="DotNetOpenAuth.OpenId" Namespace="DotNetOpenAuth.OpenId.Extensions.SimpleRegistration"

    TagPrefix="sreg" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">

<head runat="server">




    <form id="form1" runat="server">


        <rp:OpenIdButton runat="server" ImageUrl="~/images/yahoo.png" Text="Login with Yahoo!"

            ID="yahooLoginButton" Identifier="" OnLoggingIn="OpenIdLogin1_LoggingIn"



                <sreg:ClaimsRequest Email="Require" />



        <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">

            <asp:View ID="View1" runat="server">


                    Twitter setup</h2>


                    A Twitter client app must be endorsed by a Twitter user.



                    <li><a target="_blank" href="">Visit Twitter and create

                        a client app</a>. </li>

                    <li>Modify your web.config file to include your consumer key and consumer secret.</li>



            <asp:View ID="View2" runat="server">

                <asp:ImageButton ImageUrl="~/images/Sign-in-with-Twitter-darker.png" runat="server"

                    AlternateText="Sign In With Twitter" ID="signInButton" OnClick="signInButton_Click" />

                <asp:CheckBox Text="force re-login" runat="server" ID="forceLoginCheckbox" />

                <br />

                <asp:Panel runat="server" ID="loggedInPanel" Visible="false">

                    Now logged in as

                    <asp:Label Text="[name]" runat="server" ID="loggedInName" />








And the code file will be as:

using System;

using System.Collections.Generic;

using System.Web.UI;

using System.Web.UI.WebControls;

using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;

using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

using DotNetOpenAuth.OpenId.RelyingParty;

using DotNetOpenAuth.OAuth;

using DotNetOpenAuth.ApplicationBlock;

using OAuthConsumer;

public partial class _Default : System.Web.UI.Page


    protected void Page_Load(object sender, EventArgs e)


        if (TwitterConsumer.IsTwitterConsumerConfigured)


            this.MultiView1.ActiveViewIndex = 1;

            if (!IsPostBack)


                string screenName;

                int userId;

                if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId))


                    this.loggedInPanel.Visible = true;

                    this.loggedInName.Text = screenName;

                    // In a real app, the Twitter username would likely be used

                    // to log the user into the application.

                    ////FormsAuthentication.RedirectFromLoginPage(screenName, false);





    protected void OpenIdLogin1_LoggingIn(object sender, OpenIdEventArgs e)




    /// <summary>

  /// Fired upon login.

  /// </summary>

  /// <param name="sender">The source of the event.</param>

  /// <param name="e">The <see cref="DotNetOpenAuth.OpenId.RelyingParty.OpenIdEventArgs"/> instance containing the event data.</param>

  /// <remarks>

  /// Note, that straight after login, forms auth will redirect the user

  /// to their original page. So this page may never be rendererd.

  /// </remarks>

  protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) {

   State.FriendlyLoginName = e.Response.FriendlyIdentifierForDisplay;

   State.ProfileFields = e.Response.GetExtension<ClaimsResponse>();










   State.PapePolicies = e.Response.GetExtension<PolicyResponse>();


    private void prepareRequest(IAuthenticationRequest request)


        // Collect the PAPE policies requested by the user.

        List<string> policies = new List<string>();

        //foreach (ListItem item in this.papePolicies.Items)


        //    if (item.Selected)

        //    {

        //        policies.Add(item.Value);

        //    }


        // Add the PAPE extension if any policy was requested.

        var pape = new PolicyRequest();

        if (policies.Count > 0)


            foreach (string policy in policies)





        //if (this.maxAuthTimeBox.Text.Length > 0)


        //    pape.MaximumAuthenticationAge = TimeSpan.FromSeconds(double.Parse(this.maxAuthTimeBox.Text));


        if (pape.PreferredPolicies.Count > 0 || pape.MaximumAuthenticationAge.HasValue)





    protected void signInButton_Click(object sender, ImageClickEventArgs e)





Create a Class file and add the following code to that :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;

using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

/// <summary>

/// Summary description for Class1

/// </summary>

public class State


    public static ClaimsResponse ProfileFields


        get { return HttpContext.Current.Session["ProfileFields"] as ClaimsResponse; }

        set { HttpContext.Current.Session["ProfileFields"] = value; }


    public static FetchResponse FetchResponse


        get { return HttpContext.Current.Session["FetchResponse"] as FetchResponse; }

        set { HttpContext.Current.Session["FetchResponse"] = value; }


    public static string FriendlyLoginName


        get { return HttpContext.Current.Session["FriendlyUsername"] as string; }

        set { HttpContext.Current.Session["FriendlyUsername"] = value; }


    public static PolicyResponse PapePolicies


        get { return HttpContext.Current.Session["PapePolicies"] as PolicyResponse; }

        set { HttpContext.Current.Session["PapePolicies"] = value; }


    public static string GoogleAccessToken


        get { return HttpContext.Current.Session["GoogleAccessToken"] as string; }

        set { HttpContext.Current.Session["GoogleAccessToken"] = value; }


    public static void Clear()


        ProfileFields = null;

        FetchResponse = null;

        FriendlyLoginName = null;

        PapePolicies = null;

        GoogleAccessToken = null;



And add the following lines to web config:

<!-- Fill in your various consumer keys and secrets here to make the sample work. -->

    <!-- You must get these values by signing up with each individual service provider. -->

    <!-- Twitter sign-up: -->

    <add key="twitterConsumerKey" value="************" />

    <add key="twitterConsumerSecret" value="************" />

    <!-- Google sign-up: -->

    <add key="googleConsumerKey" value="anonymous" />

    <add key="googleConsumerSecret" value="anonymous" />

    <!-- Yammer sign-up: -->

    <add key="yammerConsumerKey" value="" />

    <add key="yammerConsumerSecret" value="" />

That's all