这段c#代码使用github登陆的代码有问题吗
发布于 8 年前 作者 2881099 4433 次浏览 来自 问答

官方文档:https://developer.github.com/v3/oauth/#1-redirect-users-to-request-github-access 语言不分国界,cnodejs 就用 github 了登陆啊

    [Route("/oauth/[controller]")]
    public class GithubController : HomeBaseController
    {
        [HttpGet]
        public IActionResult Step1([FromServices] IConfigurationRoot cfg) {
            string state = Guid.NewGuid().ToString();
            Session.SetString("github_state", state);
            var client_id = WebUtility.UrlEncode(cfg["oauth:github:client_id"]);
            var redirect_uri = WebUtility.UrlEncode(cfg["oauth:github:redirect_uri"]);
            return Redirect($"https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&state={state}&allow_signup=false");
        }
        [HttpGet("callback")]
        public IActionResult Callback([FromServices] IConfigurationRoot cfg, [FromQuery] string code,
            [FromQuery] string error, [FromQuery] string error_description, [FromQuery] string error_uri, [FromQuery] string state) {
            if (state != Session.GetString("github_state")) throw new Exception("state 值与 session 不一致");
            var client_id = WebUtility.UrlEncode(cfg["oauth:github:client_id"]);
            var client_secret = WebUtility.UrlEncode(cfg["oauth:github:client_secret"]);
            var redirect_uri = WebUtility.UrlEncode(cfg["oauth:github:redirect_uri"]);
			// https 请求
            HttpClientHandler clientHandler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic };
            clientHandler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true; // 检查证书
            HttpClient client = new HttpClient(clientHandler);
            StringContent content = new StringContent($"client_id={client_id}&client_secret={client_secret}&code={code}&redirect_uri={redirect_uri}&state={state}");
            var res = client.PostAsync("https://github.com/login/oauth/access_token", content).Result;
            /* 
            上面这行代码出错
            {System.Net.Http.WinHttpException: 服务器返回的信息无效或不可识别
               at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
               at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
               at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
               at System.Net.Http.WinHttpHandler.<StartRequest>d__101.MoveNext()}
            */
 
            string rt = res.Content.ReadAsStringAsync().Result;
            //access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer
            Dictionary<string, string> rtnv = new Dictionary<string, string>();
            foreach(string tmp1 in rt.Replace("&amp;", "&").Split('&')) {
                string[] tmp2 = tmp1.Split(new char[] { '=' }, 2);
                if (tmp2.Length != 2) continue;
                string k = WebUtility.UrlDecode(tmp2[0].Trim());
                string v = WebUtility.UrlDecode(tmp2[1].Trim());
                if (rtnv.ContainsKey(k)) rtnv[k] = v;
                else rtnv.Add(k, v);
            }
            string access_token;
            rtnv.TryGetValue("access_token", out access_token);
 
            return Redirect($"https://api.github.com/user?access_token?{access_token}");
        }
    }
	```
8 回复

首先,官方有sdk https://github.com/octokit/octokit.net 其二,你要说出你的问题啊

@rwing

代码中间的注释就是问题

https://github.com/login/oauth/access_token

这个access_token是不是要用用户的token来替换啊?

@liujavamail

官方文档:https://developer.github.com/v3/oauth/#1-redirect-users-to-request-github-access 我是照这个文档弄的,您的意思是缺少了什么参数吗?

var res = client.PostAsync(“https://github.com/login/oauth/access_token”, content).Result;

不好意思,看错了, 不过一般这样的情况, 你可以先debug, 把你的content打印出来, 看看有什么问题没, 把这个client.PostAsync(“https://github.com/login/oauth/access_token”, content)结果打印出来 然后把res打印出来, , 一步步看

@liujavamail 这个语法翻译成nodejs大概是这样

client.post('https://github.com/login/oauth/access_token', content, function(err, result) {
  if (err) throw err; // 就是这里报的错,大概是下面的错误
  //{System.Net.Http.WinHttpException: 服务器返回的信息无效或不可识别
   //            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   //            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   //            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   //            at System.Net.Http.WinHttpHandler.<StartRequest>d__101.MoveNext()}
});

你的content 是什么呢, 有可能是你传的content 的格式有问题

@liujavamail 应该不是 content 的问题,我试了好几种方式都不行 json, form/urlencode

回到顶部