当前位置:   article > 正文

ASP.NET实现QQ、微信、新浪微博OAuth2.0授权登录_.net 微信、微博、qq三方登录

.net 微信、微博、qq三方登录

不管是腾讯还是新浪,查看他们的API,PHP都是有完整的接口,但对C#支持似乎都不是那么完善,都没有,腾讯是完全没有,新浪是提供第三方的,而且后期还不一定升级,NND,用第三方的动辄就一个类库,各种配置还必须按照他们约定的写,烦而且乱,索性自己写,后期的扩展也容易,看过接口后,开始以为很难,参考了几个源码之后发现也不是那么难,无非是GET或POST请求他们的接口获取返回值之类的,话不多说,这里只提供几个代码共参考,抛砖引玉了。。。


我这个写法的特点是,用到了Session,使用对象实例化之后调用 Login() 跳转到登录页面,在回调页面调用Callback() 执行之后,可以从Session也可以写独立的函数(如:GetOpenID())中获取access_token或用户的唯一标识,以方便做下一步的操作。所谓绑定就是把用户的唯一标识取出,插入数据库,和帐号绑定起来。


1.首先是所有OAuth类的基类,放一些需要公用的方法

  1. public abstract class BaseOAuth
  2. {
  3. public HttpRequest Request = HttpContext.Current.Request;
  4. public HttpResponse Response = HttpContext.Current.Response;
  5. public HttpSessionState Session = HttpContext.Current.Session;
  6. public abstract void Login();
  7. public abstract string Callback();
  8. #region 内部使用函数
  9. /// <summary>
  10. /// 生成唯一随机串防CSRF攻击
  11. /// </summary>
  12. /// <returns></returns>
  13. protected string GetStateCode()
  14. {
  15. Random rand = new Random();
  16. string data = DateTime.Now.ToString("yyyyMMddHHmmssffff") + rand.Next(1, 0xf423f).ToString();
  17. MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  18. byte[] md5byte = md5.ComputeHash(UTF8Encoding.Default.GetBytes(data));
  19. return BitConverter.ToString(md5byte).Replace("-", "");
  20. }
  21. /// <summary>
  22. /// GET请求
  23. /// </summary>
  24. /// <param name="url"></param>
  25. /// <returns></returns>
  26. protected string GetRequest(string url)
  27. {
  28. HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
  29. httpWebRequest.Method = "GET";
  30. httpWebRequest.ServicePoint.Expect100Continue = false;
  31. StreamReader responseReader = null;
  32. string responseData;
  33. try
  34. {
  35. responseReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
  36. responseData = responseReader.ReadToEnd();
  37. }
  38. finally
  39. {
  40. httpWebRequest.GetResponse().GetResponseStream().Close();
  41. responseReader.Close();
  42. }
  43. return responseData;
  44. }
  45. /// <summary>
  46. /// POST请求
  47. /// </summary>
  48. /// <param name="url"></param>
  49. /// <param name="postData"></param>
  50. /// <returns></returns>
  51. protected string PostRequest(string url, string postData)
  52. {
  53. HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
  54. httpWebRequest.Method = "POST";
  55. httpWebRequest.ServicePoint.Expect100Continue = false;
  56. httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  57. //写入POST参数
  58. StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
  59. try
  60. {
  61. requestWriter.Write(postData);
  62. }
  63. finally
  64. {
  65. requestWriter.Close();
  66. }
  67. //读取请求后的结果
  68. StreamReader responseReader = null;
  69. string responseData;
  70. try
  71. {
  72. responseReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
  73. responseData = responseReader.ReadToEnd();
  74. }
  75. finally
  76. {
  77. httpWebRequest.GetResponse().GetResponseStream().Close();
  78. responseReader.Close();
  79. }
  80. return responseData;
  81. }
  82. /// <summary>
  83. /// 解析JSON
  84. /// </summary>
  85. /// <param name="strJson"></param>
  86. /// <returns></returns>
  87. protected NameValueCollection ParseJson(string strJson)
  88. {
  89. NameValueCollection mc = new NameValueCollection();
  90. Regex regex = new Regex(@"(\s*\""?([^""]*)\""?\s*\:\s*\""?([^""]*)\""?\,?)");
  91. strJson = strJson.Trim();
  92. if (strJson.StartsWith("{"))
  93. {
  94. strJson = strJson.Substring(1, strJson.Length - 2);
  95. }
  96. foreach (Match m in regex.Matches(strJson))
  97. {
  98. mc.Add(m.Groups[2].Value, m.Groups[3].Value);
  99. }
  100. return mc;
  101. }
  102. /// <summary>
  103. /// 解析URL
  104. /// </summary>
  105. /// <param name="strParams"></param>
  106. /// <returns></returns>
  107. protected NameValueCollection ParseUrlParameters(string strParams)
  108. {
  109. NameValueCollection nc = new NameValueCollection();
  110. foreach (string p in strParams.Split('&'))
  111. {
  112. string[] ps = p.Split('=');
  113. nc.Add(ps[0], ps[1]);
  114. }
  115. return nc;
  116. }
  117. #endregion
  118. }

2.QQ的OAuth类

  1. public class QQOAuth : BaseOAuth
  2. {
  3. public string AppId = ConfigurationManager.AppSettings["OAuth_QQ_AppId"];
  4. public string AppKey = ConfigurationManager.AppSettings["OAuth_QQ_AppKey"];
  5. public string RedirectUrl = ConfigurationManager.AppSettings["OAuth_QQ_RedirectUrl"];
  6. public const string GET_AUTH_CODE_URL = "https://graph.qq.com/oauth2.0/authorize";
  7. public const string GET_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
  8. public const string GET_OPENID_URL = "https://graph.qq.com/oauth2.0/me";
  9. /// <summary>
  10. /// QQ登录,跳转到登录页面
  11. /// </summary>
  12. public override void Login()
  13. {
  14. //-------生成唯一随机串防CSRF攻击
  15. string state = GetStateCode();
  16. Session["QC_State"] = state; //state 放入Session
  17. string parms = "?response_type=code&"
  18. + "client_id=" + AppId + "&redirect_uri=" + Uri.EscapeDataString(RedirectUrl) + "&state=" + state;
  19. string url = GET_AUTH_CODE_URL + parms;
  20. Response.Redirect(url); //跳转到登录页面
  21. }
  22. /// <summary>
  23. /// QQ回调函数
  24. /// </summary>
  25. /// <param name="code"></param>
  26. /// <param name="state"></param>
  27. /// <returns></returns>
  28. public override string Callback()
  29. {
  30. string code = Request.QueryString["code"];
  31. string state = Request.QueryString["state"];
  32. //--------验证state防止CSRF攻击
  33. if (state != (string)Session["QC_State"])
  34. {
  35. ShowError("30001");
  36. }
  37. string parms = "?grant_type=authorization_code&"
  38. + "client_id=" + AppId + "&redirect_uri=" + Uri.EscapeDataString(RedirectUrl)
  39. + "&client_secret=" + AppKey + "&code=" + code;
  40. string url = GET_ACCESS_TOKEN_URL + parms;
  41. string str = GetRequest(url);
  42. if (str.IndexOf("callback") != -1)
  43. {
  44. int lpos = str.IndexOf("(");
  45. int rpos = str.IndexOf(")");
  46. str = str.Substring(lpos + 1, rpos - lpos - 1);
  47. NameValueCollection msg = ParseJson(str);
  48. if (!string.IsNullOrEmpty(msg["error"]))
  49. {
  50. ShowError(msg["error"], msg["error_description"]);
  51. }
  52. }
  53. NameValueCollection token = ParseUrlParameters(str);
  54. Session["QC_AccessToken"] = token["access_token"]; //access_token 放入Session
  55. return token["access_token"];
  56. }
  57. /// <summary>
  58. /// 使用Access Token来获取用户的OpenID
  59. /// </summary>
  60. /// <param name="accessToken"></param>
  61. /// <returns></returns>
  62. public string GetOpenID()
  63. {
  64. string parms = "?access_token=" + Session["QC_AccessToken"];
  65. string url = GET_OPENID_URL + parms;
  66. string str = GetRequest(url);
  67. if (str.IndexOf("callback") != -1)
  68. {
  69. int lpos = str.IndexOf("(");
  70. int rpos = str.IndexOf(")");
  71. str = str.Substring(lpos + 1, rpos - lpos - 1);
  72. }
  73. NameValueCollection user = ParseJson(str);
  74. if (!string.IsNullOrEmpty(user["error"]))
  75. {
  76. ShowError(user["error"], user["error_description"]);
  77. }
  78. Session["QC_OpenId"] = user["openid"]; //openid 放入Session
  79. return user["openid"];
  80. }
  81. /// <summary>
  82. /// 显示错误信息
  83. /// </summary>
  84. /// <param name="code">错误编号</param>
  85. /// <param name="description">错误描述</param>
  86. private void ShowError(string code, string description = null)
  87. {
  88. if (description == null)
  89. {
  90. switch (code)
  91. {
  92. case "20001":
  93. description = "<h2>配置文件损坏或无法读取,请检查web.config</h2>";
  94. break;
  95. case "30001":
  96. description = "<h2>The state does not match. You may be a victim of CSRF.</h2>";
  97. break;
  98. case "50001":
  99. description = "<h2>可能是服务器无法请求https协议</h2>可能未开启curl支持,请尝试开启curl支持,重启web服务器,如果问题仍未解决,请联系我们";
  100. break;
  101. default:
  102. description = "<h2>系统未知错误,请联系我们</h2>";
  103. break;
  104. }
  105. Response.Write(description);
  106. Response.End();
  107. }
  108. else
  109. {
  110. Response.Write("<h3>error:<h3>" + code + "<h3>msg:<h3>" + description);
  111. Response.End();
  112. }
  113. }
  114. }

3.新浪微博的OAuth类

  1. public class SinaOAuth : BaseOAuth
  2. {
  3. public string AppKey = ConfigurationManager.AppSettings["OAuth_Sina_AppKey"];
  4. public string AppSecret = ConfigurationManager.AppSettings["OAuth_Sina_AppSecret"];
  5. public string RedirectUrl = ConfigurationManager.AppSettings["OAuth_Sina_RedirectUrl"];
  6. public const string GET_AUTH_CODE_URL = "https://api.weibo.com/oauth2/authorize";
  7. public const string GET_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
  8. public const string GET_UID_URL = "https://api.weibo.com/2/account/get_uid.json";
  9. /// <summary>
  10. /// 新浪微博登录,跳转到登录页面
  11. /// </summary>
  12. public override void Login()
  13. {
  14. //-------生成唯一随机串防CSRF攻击
  15. string state = GetStateCode();
  16. Session["Sina_State"] = state; //state 放入Session
  17. string parms = "?client_id=" + AppKey + "&redirect_uri=" + Uri.EscapeDataString(RedirectUrl)
  18. + "&state=" + state;
  19. string url = GET_AUTH_CODE_URL + parms;
  20. Response.Redirect(url); //跳转到登录页面
  21. }
  22. /// <summary>
  23. /// 新浪微博回调函数
  24. /// </summary>
  25. /// <returns></returns>
  26. public override string Callback()
  27. {
  28. string code = Request.QueryString["code"];
  29. string state = Request.QueryString["state"];
  30. //--------验证state防止CSRF攻击
  31. if (state != (string)Session["Sina_State"])
  32. {
  33. ShowError("The state does not match. You may be a victim of CSRF.");
  34. }
  35. string parms = "client_id=" + AppKey + "&client_secret=" + AppSecret
  36. + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + Uri.EscapeDataString(RedirectUrl);
  37. string str = PostRequest(GET_ACCESS_TOKEN_URL, parms);
  38. NameValueCollection user = ParseJson(str);
  39. Session["Sina_AccessToken"] = user["access_token"]; //access_token 放入Session
  40. Session["Sina_UId"] = user["uid"]; //uid 放入Session
  41. return user["access_token"];
  42. }
  43. /// <summary>
  44. /// 显示错误信息
  45. /// </summary>
  46. /// <param name="description">错误描述</param>
  47. private void ShowError(string description = null)
  48. {
  49. Response.Write("<h2>" + description + "</h2>");
  50. Response.End();
  51. }
  52. }

4.微信的OAuth类

  1. public class WeixinOAuth : BaseOAuth
  2. {
  3. public string AppId = ConfigurationManager.AppSettings["OAuth_Weixin_AppId"];
  4. public string AppSecret = ConfigurationManager.AppSettings["OAuth_Weixin_AppSecret"];
  5. public string RedirectUrl = ConfigurationManager.AppSettings["OAuth_Weixin_RedirectUrl"];
  6. public const string GET_AUTH_CODE_URL = "https://open.weixin.qq.com/connect/qrconnect";
  7. public const string GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
  8. public const string GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
  9. /// <summary>
  10. /// 微信登录,跳转到登录页面
  11. /// </summary>
  12. public override void Login()
  13. {
  14. //-------生成唯一随机串防CSRF攻击
  15. string state = GetStateCode();
  16. Session["Weixin_State"] = state; //state 放入Session
  17. string parms = "?appid=" + AppId
  18. + "&redirect_uri=" + Uri.EscapeDataString(RedirectUrl) + "&response_type=code&scope=snsapi_login"
  19. + "&state=" + state + "#wechat_redirect";
  20. string url = GET_AUTH_CODE_URL + parms;
  21. Response.Redirect(url); //跳转到登录页面
  22. }
  23. /// <summary>
  24. /// 微信回调函数
  25. /// </summary>
  26. /// <param name="code"></param>
  27. /// <param name="state"></param>
  28. /// <returns></returns>
  29. public override string Callback()
  30. {
  31. string code = Request.QueryString["code"];
  32. string state = Request.QueryString["state"];
  33. //--------验证state防止CSRF攻击
  34. if (state != (string)Session["Weixin_State"])
  35. {
  36. ShowError("30001");
  37. }
  38. string parms = "?appid=" + AppId + "&secret=" + AppSecret
  39. + "&code=" + code + "&grant_type=authorization_code";
  40. string url = GET_ACCESS_TOKEN_URL + parms;
  41. string str = GetRequest(url);
  42. NameValueCollection msg = ParseJson(str);
  43. if (!string.IsNullOrEmpty(msg["errcode"]))
  44. {
  45. ShowError(msg["errcode"], msg["errmsg"]);
  46. }
  47. Session["Weixin_AccessToken"] = msg["access_token"]; //access_token 放入Session
  48. Session["Weixin_OpenId"] = msg["openid"]; //access_token 放入Session
  49. return msg["access_token"];
  50. }
  51. /// <summary>
  52. /// 显示错误信息
  53. /// </summary>
  54. /// <param name="code">错误编号</param>
  55. /// <param name="description">错误描述</param>
  56. private void ShowError(string code, string description = null)
  57. {
  58. if (description == null)
  59. {
  60. switch (code)
  61. {
  62. case "20001":
  63. description = "<h2>配置文件损坏或无法读取,请检查web.config</h2>";
  64. break;
  65. case "30001":
  66. description = "<h2>The state does not match. You may be a victim of CSRF.</h2>";
  67. break;
  68. case "50001":
  69. description = "<h2>接口未授权</h2>";
  70. break;
  71. default:
  72. description = "<h2>系统未知错误,请联系我们</h2>";
  73. break;
  74. }
  75. Response.Write(description);
  76. Response.End();
  77. }
  78. else
  79. {
  80. Response.Write("<h3>error:<h3>" + code + "<h3>msg:<h3>" + description);
  81. Response.End();
  82. }
  83. }
  84. }

5.web.config配置信息

  1. <appSettings>
  2. <!--QQ登录相关配置-->
  3. <add key="OAuth_QQ_AppId" value="123456789" />
  4. <add key="OAuth_QQ_AppKey" value="25f9e794323b453885f5181f1b624d0b" />
  5. <add key="OAuth_QQ_RedirectUrl" value="http://www.domain.com/oauth20/qqcallback.aspx" />
  6. <!--新浪微博登录相关配置-->
  7. <add key="OAuth_Sina_AppKey" value="123456789" />
  8. <add key="OAuth_Sina_AppSecret" value="25f9e794323b453885f5181f1b624d0b" />
  9. <add key="OAuth_Sina_RedirectUrl" value="http://www.domain.com/oauth20/sinacallback.aspx" />
  10. <!--微信登录相关配置-->
  11. <add key="OAuth_Weixin_AppId" value="wx123456789123" />
  12. <add key="OAuth_Weixin_AppSecret" value="25f9e794323b453885f5181f1b624d0b" />
  13. <add key="OAuth_Weixin_RedirectUrl" value="http://www.domain.com/oauth20/weixincallback.aspx" />
  14. </appSettings>

原文地址: ASP.NET实现QQ、微信、新浪微博OAuth2.0授权登录

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/270048
推荐阅读