使用令牌Oauth2 c#

时间:2018-06-27 08:04:14

标签: c# api

我想使用API​​来获取一些数据。我所拥有的信息是身份验证URL,访问令牌URL,客户端ID,机密,API端点,范围,用户名和密码。我看到了很多例子,但是每次都缺少一些东西。请帮忙。

谢谢。

1 个答案:

答案 0 :(得分:0)

请检查我的代码和我所拥有的信息。

        Auth URL : https://nightswatch-trial.ikentoo.com/oauth/authorize
        Access Token URL : https://nightswatch-trial.ikentoo.com/oauth/token
        The base API Endpoint is : https://api-trial.ikentoo.com/f

        string url = "https://nightswatch-trial.ikentoo.com/";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Credentials = new NetworkCredential("username", "password");
        //request.CookieContainer = myContainer;
        request.PreAuthenticate = true;
        string accessToken = "";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            NameValueCollection urlParameters = HttpUtility.ParseQueryString(response.ResponseUri.Query);

            // extract the access token from the url.

            accessToken = urlParameters["access_token"];
        }

        using (HttpClient client = new HttpClient())
        {
            string TokenURI = "https://nightswatch-trial.ikentoo.com/oauth/token";
            client.BaseAddress = new Uri(TokenURI);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            object REDIRECTURL = "https://api-trial.ikentoo.com/f/14886356647938/dailyFinancials";
            object YourCliendID = "clientid";
            object YourSecret = "secretcode";
            var requestContent = string.Format("grant_type=authorization_code&redirect_uri={0}&scope=wow.profile&client_id={1}&client_secret={2}",
                REDIRECTURL, YourCliendID, YourSecret);

            var content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");

            var response = await client.PostAsync(client.BaseAddress, content);
            var result = await response.Content.ReadAsStringAsync();
        }