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 http://dotnetopenauth.net/
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <rp:OpenIdButton runat="server" ImageUrl="~/images/yahoo.png" Text="Login with Yahoo!" ID="yahooLoginButton" Identifier="https://me.yahoo.com/" OnLoggingIn="OpenIdLogin1_LoggingIn" OnLoggedIn="OpenIdLogin1_LoggedIn"> <Extensions> <sreg:ClaimsRequest Email="Require" /> </Extensions> </rp:OpenIdButton> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> <asp:View ID="View1" runat="server"> <h2> Twitter setup</h2> <p> A Twitter client app must be endorsed by a Twitter user. </p> <ol> <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create a client app</a>. </li> <li>Modify your web.config file to include your consumer key and consumer secret.</li> </ol> </asp:View> <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" /> </asp:Panel> </asp:View> </asp:MultiView> </div> </form> </body> </html>
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) { this.prepareRequest(e.Request); } /// <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>(); //Response.Write(State.ProfileFields.BirthDate.Value.ToString()); Response.Write(State.ProfileFields.Country); Response.Write(State.ProfileFields.Email); Response.Write(State.ProfileFields.FullName); Response.Write(State.ProfileFields.Gender); Response.Write(State.ProfileFields.MailAddress.DisplayName); Response.Write(State.ProfileFields.Nickname); Response.Write(State.ProfileFields.PostalCode); 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) { pape.PreferredPolicies.Add(policy); } } //if (this.maxAuthTimeBox.Text.Length > 0) //{ // pape.MaximumAuthenticationAge = TimeSpan.FromSeconds(double.Parse(this.maxAuthTimeBox.Text)); //} if (pape.PreferredPolicies.Count > 0 || pape.MaximumAuthenticationAge.HasValue) { request.AddExtension(pape); } } protected void signInButton_Click(object sender, ImageClickEventArgs e) { TwitterConsumer.StartSignInWithTwitter(this.forceLoginCheckbox.Checked).Send(); } }
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: https://twitter.com/oauth_clients --> <add key="twitterConsumerKey" value="************" /> <add key="twitterConsumerSecret" value="************" /> <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> <add key="googleConsumerKey" value="anonymous" /> <add key="googleConsumerSecret" value="anonymous" /> <!-- Yammer sign-up: https://www.yammer.com/client_applications/new --> <add key="yammerConsumerKey" value="" /> <add key="yammerConsumerSecret" value="" />
That's all
I syntax highlighter for your blog would be nice :-)
ReplyDelete