简体   繁体   English

链接到C#中的当前状态更新,获取错误(401)未经授权

[英]Linked In current-status update in c#, Getting Error (401) Unauthorized

Basically i want to save AccessToken, AccessTokenSecret and Verifier in database and when i want to post status update in 'linked in' on behalf of user i can. 基本上,我想将AccessToken,AccessTokenSecret和Verifier保存在数据库中,并且当我想代表用户以“链接入”状态发布状态更新时。

Getting these access tokens first time and then using it, i can successfully update status. 第一次获取这些访问令牌,然后再使用它,我就可以成功更新状态。 But i stored it and then after 20-30 minutes, if i try same update status call with that stored tokens , i am getting 401 error. 但是我存储了它,然后在20-30分钟后,如果我尝试使用存储的令牌进行相同的更新状态调用,则会收到401错误。

Is it right way to store tokens and use it later . 是存储令牌并在以后使用的正确方法。 Or every time user need to show allow permission screen and have to get new tokens? 还是每次用户需要显示允许权限屏幕并必须获取新令牌时?

Below is my function. 下面是我的功能。 i am using this library 我正在使用这个图书馆

public string makeRequestForStatusUpdateOnLinkedIn(String txtAccessToken, String txtAccessTokenSecret, String txtoAuth_verifier,String status)
        {
 private oAuthLinkedIn _oauth = new oAuthLinkedIn()
            _oauth.Token = txtAccessToken;
            _oauth.TokenSecret = txtAccessTokenSecret;
            _oauth.Verifier = txtoAuth_verifier;

            string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            xml += "<current-status>" + status + ".</current-status>";


            string response = _oauth.APIWebRequest("PUT", "http://api.linkedin.com/v1/people/~/current-status", xml);

            if (response == "")
                return "Your new status updated successfully !";
            else
            {
                return "Sorry ! Error at server side!";
            }
        }

Finally without using any others library. 最后不用任何其他库。 I just follow steps of LinkedIn documentation and get what i want.Below is code which solve my problem , may help others. 我只是按照LinkedIn文档的步骤操作即可得到我想要的。下面是解决我的问题的代码,可能会对他人有所帮助。

    using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using OAuth2;
namespace WebApplication2
{
    public partial class SamplePage : System.Web.UI.Page
    {
        public enum Method { GET, POST, PUT, DELETE };

        public const String apikey = "YOURAPP_API_KEY";
        public const String Secretkey = "YOUR_APP_SECRETKEY";
        public const String linkedInPeapleURL = "https://api.linkedin.com/v1/people/~";
        public const String generateAuthorizationCode = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code";
        public const String state= "qwertyytrewq123";
        public const String redirectURI = "http://localhost:17681/SamplePage.aspx";
        public const String generateAccessToeknURL = "https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code";
        public String code="";
        public const String useAccessToeknURL = "https://api.linkedin.com/v1/people/~?oauth2_access_token=";
        public const String scope = "r_basicprofile";// r_fullprofile r_emailaddress r_network r_contactinfo rw_nusrw_groups w_messages"; 
        // OR SET permission while create Application in linked in
        public String AccessToken;

        protected void Page_Load(object sender, EventArgs e)
        {

            //Redirect
            string url = getAuthorizationURL();

          //  url=HttpUtility.UrlEncode(url);

            //WebRequest(Method.GET, url, "");

            if (Request.QueryString["code"] == null)
            {

                Response.Redirect(url, true);
            }
            else
            {
                code = Request.QueryString["code"];
                String response = WebRequest(Method.GET, getAccessToeknURL(), "");

                JObject jobj = JObject.Parse(response);

                AccessToken = jobj["access_token"].ToString();

                response = WebRequest(Method.GET, linkedInPeapleURL+ "?oauth2_access_token=" + AccessToken, ""); // get basic detail
               // response = WebRequest(Method.GET, linkedInPeapleURL + "/email-address" + "?oauth2_access_token=" + AccessToken, ""); // get Email id




                //GET Request 
            }



            // POST request



            //GET Request 





        }
        public string getAccessToeknURL()
        {
            String url = "";

            url = generateAccessToeknURL + "&code=" + code + "&redirect_uri=" + redirectURI + "&client_id=" + apikey + "&client_secret=" + Secretkey;

            return url;
        }
        private String getAuthorizationURL()
        {
            String response = generateAuthorizationCode + "&client_id=" + apikey +"&state=" + state + "&redirect_uri=" + redirectURI;
           return response;
        }

        public string WebRequest(Method method, string url, string postData)
        {
            HttpWebRequest webRequest = null;
            StreamWriter requestWriter = null;
            string responseData = "";

            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;
            //webRequest.UserAgent  = "Identify your application please.";
            //webRequest.Timeout = 20000;

            if (method == Method.POST)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //POST the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            //webRequest.ContentType = "text/plain";
            responseData = WebResponseGet(webRequest);

            webRequest = null;

            return responseData;

        }
        public string WebResponseGet(HttpWebRequest webRequest)
        {

            StreamReader responseReader = null;
            string responseData = "";

            try
            {
                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch
            {
                throw;
            }
            finally
            {
                webRequest.GetResponse().GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }

            return responseData;
        }

    }
}

Please try this code 请尝试此代码

  protected void Page_Load(object sender, EventArgs e)    

    {    

    // create from config file    

    var config = LinkedInApiConfiguration.FromAppSettings("LogiDemo.LinkedInConnect");    

    // or manually    

    // var config = LinkedInApiConfiguration("api key", "api secret key");  


    // get the APIs client


    var api = new LinkedInApi(config);   


    var scope = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;    

    var state = Guid.NewGuid().ToString();    

    var redirectUrl = "http://localhost:49965/WebForm1.aspx";

    var url = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUrl);   

    Response.Redirect(url.OriginalString);    

    }

Refer article: http://blog.logiticks.com/post/2015/06/28/how-to-retrieve-all-possible-information-about-a-linkedin-account-using-asp-net-c 请参阅文章: http : //blog.logiticks.com/post/2015/06/28/how-to-retrieve-all-possible-information-about-a-linkedin-account-using-asp-net-c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#窗口应用程序中SSRS报告呈现中出现错误:请求失败,HTTP状态为401:未经授权 - Getting Error in SSRS report rendering in C# window application: The request failed with HTTP status 401: Unauthorized C#LinkedIn API dquail Oauth从当前状态更改为新状态 <share> api - c# LinkedIn API dquail Oauth changing from current-status to new <share> api httpclient api 在 c# 中出现未经授权的 401 错误 - httpclient api unauthorized 401 error in c# C#JIRA工作日志更新错误“远程服务器返回错误:(401)未经授权。” - C# JIRA work-log update error “The remote server returned an error: (401) Unauthorized.” 从我的C#应用​​程序访问webDav文件夹时出现401未经授权的错误? - Getting 401 unauthorized error while accessing webDav folder from my C# application? 我在 c# wpf 中使用 spotify api 未经授权收到错误 401 - im getting a error 401 unauthorized using the spotify api in c# wpf 从ajax调用本地C#Web服务,错误401未经授权 - Call a local C# webservice from ajax , 401 error Unauthorized 无法连接到C#中的URL,并显示401未经授权的错误 - Cannot connect to url in C# with 401 unauthorized error C# 远程服务器返回错误:(401) Unauthorized - C# The remote server returned an error: (401) Unauthorized 使用来自 Sharepoint 和 C# 的链接时出错((401)未经授权) - Error when use link from Sharepoint with C# ( (401) unauthorized )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM