2012-07-11 31 views
6

¿Cómo se implementaría un método de inicio de sesión para Linkedin, para que la gente simplemente haga clic en un botón y use su cuenta de Linkedin para iniciar sesión, al igual que en Facebook o Twitter? Ambos usan OAuth, pero encontré bibliotecas específicas para ellos que son muy fáciles de usar. Para Linkedin, solo encontré un código de muestra en DotNetOpenAuth, pero no puedo hacer que tenga ningún sentido de.Iniciar sesión con Linkedin

¿Hay alguna biblioteca que pueda usar para facilitar una función de inicio de sesión para Linkedin? ¿O algún tutorial sobre cómo hacer eso en ASP.NET MVC con DotNetOpenAuth 4?

+0

No me he equivocado con OAuth todavía, no hay más que leer sobre él de todos modos. Sin embargo, hice un Google rápido y encontré esta página en linkedin: https://developer.linkedin.com/documents/quick-start-guide Por lo que puedo decir, esto + DotNetOpenAuth debería hacer el trabajo. (No estoy escribiendo una respuesta porque siento que no estoy 100% seguro de estar aquí, y no tengo ninguna experiencia del mundo real sobre el tema, aún :)) – Onkelborg

+0

@Onkelborg, encontré que , pero DNOA es un poco ... complicado para OAuth y las muestras son viejas. Peor aún, están llenos de código de WebForms y estructuras de datos personalizadas, lo que hace que sea mucho más difícil de entender. – CMircea

Respuesta

4

Esto es lo que parece ser una muestra bastante sólido

http://mrsarker.wordpress.com/2011/08/20/linkedin-rest-api-in-asp-net-mvc/

[HandleError] 
public class LinkedInController : Controller 
{ 
    public ActionResult index() 
    { 
     return AuthenticateToLinkedIn(); 
    } 

    static string token_secret = ""; 
    public ActionResult AuthenticateToLinkedIn() 
    { 
     var credentials = new OAuthCredentials 
     { 
      CallbackUrl = "http://localhost/home/callback", 
      ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"], 
      ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"], 
      Verifier = "123456", 
      Type = OAuthType.RequestToken 
     }; 

     var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials }; 
     var request = new RestRequest { Path = "requestToken" }; 
     RestResponse response = client.Request(request); 

     token = response.Content.Split('&').Where(s => s.StartsWith("oauth_token=")).Single().Split('=')[1]; 
     token_secret = response.Content.Split('&').Where(s => s.StartsWith("oauth_token_secret=")).Single().Split('=')[1]; 
     Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token); 
     return null; 
    } 

    string token = ""; 
    string verifier = ""; 
    public ActionResult Callback() 
    { 
     token = Request["oauth_token"]; 
     verifier = Request["oauth_verifier"]; 
     var credentials = new OAuthCredentials 
     { 
      ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"], 
      ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"], 
      Token = token, 
      TokenSecret = token_secret, 
      Verifier = verifier, 
      Type = OAuthType.AccessToken, 
      ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 
      SignatureMethod = OAuthSignatureMethod.HmacSha1, 
      Version = "1.0" 
     }; 

     var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials, Method = WebMethod.Post }; 
     var request = new RestRequest { Path = "accessToken" }; 
     RestResponse response = client.Request(request); 
     string content = response.Content; 


     string accessToken = response.Content.Split('&').Where(s => s.StartsWith("oauth_token=")).Single().Split('=')[1]; 
     string accessTokenSecret = response.Content.Split('&').Where(s => s.StartsWith("oauth_token_secret=")).Single().Split('=')[1]; 

     var company = new LinkedInService(accessToken, accessTokenSecret).GetCompany(162479);    

     // Some commented call to API 
     //company = new LinkedInService(accessToken, accessTokenSecret).GetCompanyByUniversalName("linkedin"); 
     // var companies = new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByEmailDomain("apple.com");    
     // var companies1 = new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByEmailDomain("linkedin.com");   
     // var companies2= new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByIdAnduniversalName("162479", "linkedin"); 
     //var people = new LinkedInService(accessToken, accessTokenSecret).GetPersonById("f7cp5sKscd"); 
     //var people = new LinkedInService(accessToken, accessTokenSecret).GetCurrentUser(); 

     //string url = Url.Encode("http://bd.linkedin.com/pub/rakibul-islam/37/522/653"); 
     //var people = new LinkedInService(accessToken, accessTokenSecret).GetPeoPleByPublicProfileUrl(url); 
     //var peopleSearchresult = new LinkedInService(accessToken, accessTokenSecret).SearchPeopleByKeyWord("Princes"); 

     var peopleSearchresult = new LinkedInService(accessToken, accessTokenSecret).GetPeopleByFirstName("Mizan"); 
     String companyName = company.Name; 
     return Content(companyName);    
    } 
} 


public class LinkedInService 
{ 
    private const string URL_BASE = "http://api.linkedin.com/v1"; 
    public static string ConsumerKey { get { return ConfigurationManager.AppSettings["ConsumerKey"]; } } 
    public static string ConsumerKeySecret { get { return ConfigurationManager.AppSettings["ConsumerSecret"]; } } 
    public string AccessToken { get; set; } 
    public string AccessTokenSecret { get; set; } 

    public LinkedInService(string accessToken, string accessTokenSecret) 
    { 
     this.AccessToken = accessToken; 
     this.AccessTokenSecret = accessTokenSecret; 
    } 

    private OAuthCredentials AccessCredentials 
    { 
     get 
     { 
      return new OAuthCredentials 
      { 
       Type = OAuthType.AccessToken, 
       SignatureMethod = OAuthSignatureMethod.HmacSha1, 
       ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 
       ConsumerKey = ConsumerKey, 
       ConsumerSecret = ConsumerKeySecret, 
       Token = AccessToken, 
       TokenSecret = AccessTokenSecret 
      }; 
     } 
    } 

    #region Helper 

    private RestResponse GetResponse(string path) 
    { 
     var client = new RestClient() 
     { 
      Authority = URL_BASE, 
      Credentials = AccessCredentials, 
      Method = WebMethod.Get 
     }; 

     var request = new RestRequest { Path = path }; 

     return client.Request(request); 
    } 

    private T Deserialize(string xmlContent) 
    { 
     MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(xmlContent)); 
     XmlSerializer deserializer = new XmlSerializer(typeof(T)); 
     return (T)deserializer.Deserialize(new StringReader(xmlContent)); 
    } 

    #endregion 

    // methods removed for brevity. check the original link for full source 

} 
+0

¿Hay alguna manera de almacenar datos personalizados que se devolverán después de la llamada? Por ejemplo, quiero almacenar la URL de la página original, para redirigir al usuario después de que el proceso de inicio de sesión haya finalizado. – CMircea

+0

@MirceaChirea Tiene esta línea CallbackUrl = "http: // localhost/home/callback", creo que solo tiene que cambiar esa línea y anexar algunos parámetros – Onkelborg

+0

@Onkelborg, * facepalm *, ¡Nunca pensé en eso, jaja! – CMircea

0

Si no desea codificar por sí mismo, siempre se puede buscar en una solución de terceros, como solución RPX de JanRain : http://developers.janrain.com/. Le dará el inicio de sesión de LinkedIn y muchos más.

+0

Decidí no agregar un único punto de falla al proceso de inicio de sesión de mi sitio web, así como las tarifas recurrentes. – CMircea

Cuestiones relacionadas