Asp. NET to achieve QQ, micro-letter, Sina Weibo OAuth2.0 authorized Login [Original]_ practical skills

Source: Internet
Author: User
Tags curl httpcontext md5 oauth openid csrf attack

Whether it's Tencent or Sina, see their api,php are all have a complete interface, but for C # support seems to be not so perfect, there is no, Tencent is completely no, Sina is to provide a third party, and the latter is not necessarily upgraded, NND, with a third party at every turn on a class library, The various configurations must also be written according to their agreement, annoying and disorderly, simply write their own, later expansion is also easy, after looking at the interface, began to think it is difficult to refer to a few source code after the discovery is not so difficult, nothing more than GET or POST request their interface to obtain return value and so on, words not to say, Here only a few code for reference, the ...

The feature of my writing is that, using the session, after using the object instantiation call login () jump to the login page, after the callback page call callback () execution, you can also write a separate function from the session (such as: Getopenid () Gets the unique identification of the Access_token or user to facilitate the next steps. The so-called binding is to remove the user's unique identity, insert the database, and the account binding.

1. First is the base class of all OAuth classes, put some methods that need to be shared

Public abstract class Baseoauth {public HttpRequest Request = HttpContext.Current.Request;
  Public HttpResponse Response = HttpContext.Current.Response;

  Public HttpSessionState session = HttpContext.Current.Session;
  public abstract void Login ();

  Public abstract string Callback ();
  #region Internal Use functions///<summary>///generate unique random string csrf attack///</summary>///<returns></returns>
    Protected string Getstatecode () {Random rand = new Random (); String data = DateTime.Now.ToString ("yyyymmddhhmmssffff") + Rand. Next (1, 0xf423f).

    ToString ();

    MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider ();

    byte[] Md5byte = Md5.computehash (UTF8Encoding.Default.GetBytes (data)); Return bitconverter.tostring (Md5byte).

  Replace ("-", ""); ///<summary>///GET request///</summary>///<param name= "url" ></param>///<returns ></returns> protected string getrequest (string url) {HttpWebRequestHttpWebRequest = System.Net.WebRequest.Create (URL) as HttpWebRequest;
    Httpwebrequest.method = "Get";

    HttpWebRequest.ServicePoint.Expect100Continue = false;
    StreamReader responsereader = null;
    String ResponseData; try {responsereader = new StreamReader (HttpWebRequest.GetResponse ().
      GetResponseStream ());
    ResponseData = Responsereader.readtoend (); finally {HttpWebRequest.GetResponse (). GetResponseStream ().
      Close ();
    Responsereader.close ();
  return responsedata; ///<summary>///POST request///</summary>///<param name= "url" ></param>///<param  Name= "PostData" ></param>///<returns></returns> protected string postrequest (string URL, string
    PostData) {HttpWebRequest HttpWebRequest = System.Net.WebRequest.Create (URL) as HttpWebRequest;
    Httpwebrequest.method = "POST";
    HttpWebRequest.ServicePoint.Expect100Continue = false; Httpwebrequest.conTenttype = "application/x-www-form-urlencoded";
    Write post parameter StreamWriter requestwriter = new StreamWriter (Httpwebrequest.getrequeststream ());
    try {requestwriter.write (postdata);
    finally {requestwriter.close ();
    }//Read the result of the request StreamReader responsereader = null;
    String ResponseData; try {responsereader = new StreamReader (HttpWebRequest.GetResponse ().
      GetResponseStream ());
    ResponseData = Responsereader.readtoend (); finally {HttpWebRequest.GetResponse (). GetResponseStream ().
      Close ();
    Responsereader.close ();
  return responsedata; ///<summary>///parsing json///</summary>///<param name= "Strjson" ></param>///<re turns></returns> protected NameValueCollection Parsejson (string strjson) {NameValueCollection mc = new N
    Amevaluecollection (); Regex regex = new Regex (\s*\ ""? [^ ""]*) \ "" \s*\:\s*\ ""?
    ([^""]*)\""?\,?)"); STrjson = Strjson.trim ();
    if (Strjson.startswith ("{")) {Strjson = strjson.substring (1, strjson.length-2); foreach (Match m in regex. Matches (Strjson)) {MC. ADD (M.groups[2]. Value, M.groups[3].
    Value);
  Return to MC; ///<summary>///Resolution URL///</summary>///<param name= "Strparams" ></param>///<r eturns></returns> protected NameValueCollection parseurlparameters (string strparams) {Namevaluecollectio
    n NC = new NameValueCollection ();
      foreach (String p in Strparams.split (' & ')) {string[] ps = p.split (' = '); nc.
    ADD (Ps[0], ps[1]);
  } return NC; } #endregion}

the OAuth class

for 2.QQ

public class Qqoauth:baseoauth {public string AppId = configurationmanager.appsettings["Oauth_qq_appid"];
  public string appkey = configurationmanager.appsettings["Oauth_qq_appkey"];

  public string redirecturl = configurationmanager.appsettings["Oauth_qq_redirecturl"];
  Public Const string Get_auth_code_url = "Https://graph.qq.com/oauth2.0/authorize";
  Public Const string Get_access_token_url = "Https://graph.qq.com/oauth2.0/token";

  Public Const string Get_openid_url = "Https://graph.qq.com/oauth2.0/me"; <summary>///QQ Login, jump to login page///</summary> public override void Login () {//-------generate a single random string to prevent CSRF
    Attack string state = Getstatecode (); session["qc_state"] = State; State into session string parms = "?response_type=code&" + "client_id=" + AppId + "&redirect_uri=" + URI .

    Escapedatastring (RedirectURL) + "&state=" + state;
    String url = get_auth_code_url + parms; Response.Redirect (URL); Jump to login page}///<summaRy>///QQ callback function///</summary>///<param name= "code" ></param>///<param name= "state" >& Lt;/param>///<returns></returns> public override string Callback () {String code = Request.quer
    ystring["Code"];

    string state = Request.querystring[' state '];
    --------verify state to prevent CSRF attack if (state!= (string) session["Qc_state") {ShowError ("30001"); String parms = "?grant_type=authorization_code&" + "client_id=" + AppId + "&redirect_uri=" + Uri.esca

    Pedatastring (RedirectURL) + "&client_secret=" + Appkey + "&code=" + code;
    String url = get_access_token_url + parms;

    String str = getrequest (URL); if (str. IndexOf ("callback")!=-1) {int lpos = str.
      IndexOf ("("); int rpos = str.
      IndexOf (")"); str = str.
      Substring (Lpos + 1, rpos-lpos-1);
      NameValueCollection msg = Parsejson (str); if (!string. IsNullOrEmpty (msg["error")) {ShowError (msg["error"], msg["error_description"]);
    } NameValueCollection token = parseurlparameters (str); session["Qc_accesstoken"] = token["Access_token"];
  Access_token into the session return token["Access_token"]; ///<summary>///uses access token to obtain the user's OpenID///</summary>///<param name= "Accesstoken" &GT;&L t;/param>///<returns></returns> public string Getopenid () {string parms = "? access_token=" + S

    ession["Qc_accesstoken"];
    String url = get_openid_url + parms;

    String str = getrequest (URL); if (str. IndexOf ("callback")!=-1) {int lpos = str.
      IndexOf ("("); int rpos = str.
      IndexOf (")"); str = str.
    Substring (Lpos + 1, rpos-lpos-1);

    } NameValueCollection user = Parsejson (str); if (!string.
    IsNullOrEmpty (user["error")) {ShowError (user["error"], user["error_description"]); } session["Qc_openid"] = user["OpenId"]; OpenID put session return USer["OpenID"]; ///<summary>///Display error message///</summary>///<param name= "code" > Error number </param>///<p Aram name= "description" > Error description </param> private void ShowError (string code, string description = null) {if
    (Description = NULL) {switch (code) {case "20001": Description =  

3. Sina Weibo's OAuth class

public class Sinaoauth:baseoauth {public string appkey = configurationmanager.appsettings["Oauth_sina_appkey"];
  public string Appsecret = configurationmanager.appsettings["Oauth_sina_appsecret"];

  public string redirecturl = configurationmanager.appsettings["Oauth_sina_redirecturl"];
  Public Const string Get_auth_code_url = "Https://api.weibo.com/oauth2/authorize";
  Public Const string Get_access_token_url = "Https://api.weibo.com/oauth2/access_token";

  Public Const string Get_uid_url = "Https://api.weibo.com/2/account/get_uid.json"; <summary>///Sina Weibo login, jump to login page///</summary> public override void Login () {//-------generate unique random string CS
    RF attack String state = Getstatecode (); session["sina_state"] = State;
      State into session string parms = "client_id=" + Appkey + "&redirect_uri=" + uri.escapedatastring (RedirectURL)

    + "&state=" + state;
    String url = get_auth_code_url + parms; Response.Redirect (URL); Jump to login page}///&LT;summary>///Sina Weibo callback function///</summary>///<returns></returns> public override string Callbac
    K () {String code = request.querystring["Code"];

    string state = Request.querystring[' state '];  --------Verify state prevents the CSRF attack if (state!= (string) session["Sina_state"]) {ShowError ("The state does not match.")

    You may be a victim of CSRF. "); String parms = "client_id=" + Appkey + "&client_secret=" + Appsecret + "&grant_type=authorization_code&c

    Ode= "+ code +" &redirect_uri= "+ uri.escapedatastring (RedirectURL);

    String str = Postrequest (Get_access_token_url, parms);

    NameValueCollection user = Parsejson (str); session["Sina_accesstoken"] = user["Access_token"]; Access_token into session session["sina_uid"] = user["UId"];
  The UID is put in session return user["Access_token"]; ///<summary>///Display error message///</summary>///<param name= "description" > Error description </param> P Rivate void ShowError (string description = null) {Response.Write (" 

4. Micro-OAuth class

public class Weixinoauth:baseoauth {public string AppId = configurationmanager.appsettings["Oauth_weixin_appid"];
  public string Appsecret = configurationmanager.appsettings["Oauth_weixin_appsecret"];

  public string redirecturl = configurationmanager.appsettings["Oauth_weixin_redirecturl"];
  Public Const string Get_auth_code_url = "Https://open.weixin.qq.com/connect/qrconnect";
  Public Const string Get_access_token_url = "Https://api.weixin.qq.com/sns/oauth2/access_token";

  Public Const string Get_userinfo_url = "Https://api.weixin.qq.com/sns/userinfo"; <summary>///Micro-letter login, jump to login page///</summary> public override void Login () {//-------generate a single random string to prevent CSRF
    Attack string state = Getstatecode (); session["weixin_state"] = State;  State into session string parms = "appid=" + AppID + "&redirect_uri=" + uri.escapedatastring (RedirectURL) +

   "&response_type=code&scope=snsapi_login" + "&state=" + state + "#wechat_redirect"; String url = get_auth_code_url + parms; Response.Redirect (URL); Jump to login page}///<summary>///micro-mail callback function///</summary>///<param name= "code" ></param>/
    <param name= ' state ' ></param>///<returns></returns> public override string Callback () {
    String code = request.querystring["Code"];

    string state = Request.querystring[' state '];
    --------verify state to prevent CSRF attack if (state!= (string) session["Weixin_state") {ShowError ("30001"); } string parms = "? appid=" + AppID + "&secret=" + Appsecret + "&code=" + code + "&grant_type=author"

    Ization_code ";
    String url = get_access_token_url + parms;


    String str = getrequest (URL);
    NameValueCollection msg = Parsejson (str); if (!string.
    IsNullOrEmpty (msg["Errcode"])) {ShowError (msg["Errcode"], msg["errmsg"]); } session["Weixin_accesstoken"] = msg["Access_token"]; Access_token into session session["WeixIn_openid "] = msg[" OpenId "];
  Access_token into the session return msg["Access_token"]; ///<summary>///Display error message///</summary>///<param name= "code" > Error number </param>///<  param name= "description" > Error description </param> private void ShowError (string code, string description = null) {if
    (Description = NULL) {switch (code) {case "20001": Description =  

5.web.config configuration information

<appSettings>
    <!--QQ Login related configuration-->
    <add key= "oauth_qq_appid" value= "123456789"/>
    < Add key= "Oauth_qq_appkey" value= "25f9e794323b453885f5181f1b624d0b"/> <add key=
    "Oauth_qq_redirecturl" Value= "http://www.domain.com/oauth20/qqcallback.aspx"/>

    <!--Sina Weibo login related configuration-->
    <add key= "Oauth_ Sina_appkey "value=" 123456789 "/> <add key=" Oauth_sina_appsecret "value="
    25f9e794323b453885f5181f1b624d0b "/>
    <add key=" Oauth_sina_redirecturl "value=" http://www.domain.com/ Oauth20/sinacallback.aspx "/>

    <!--micro-letter Login related configuration--> <add key=" oauth_weixin_appid "value="
    Wx123456789123 "/> <add key= oauth_weixin_appsecret" value= "25f9e794323b453885f5181f1b624d0b"/>
    <add key= "Oauth_weixin_redirecturl" value= "http://www.domain.com/oauth20/weixincallback.aspx"/>
</appSettings>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.