How to integrate QQ login function with ASP

Source: Internet
Author: User
Tags openid

Reference is made to the "ASP. QQ2.0 Login code example" and "Login integration for-QQ interconnect authentication (ASP. NET version)".

usingSystem;usingSystem.Net;usingSystem.Text;usingSystem.IO;usingSystem.Collections.Specialized;usingSystem.Data;usingSystem.Configuration;usingNewtonsoft.Json.Linq;usingscratchline.database;usingSystem.Web.Security;namespacescratchline.cn{ Public Partial classLogin_qq:System.Web.UI.Page {Private StaticRandom Rndseed =NewRandom ();  Public stringgeneraterndnonce () {return(Rndseed.next (1,0xf423f). ToString ("000000") + Rndseed.next (1,0xf423f). ToString ("000000")); }         Public stringFile_get_contents (stringURL, Encoding encode) {HttpWebRequest Request=(HttpWebRequest) httpwebrequest.create (URL); WebResponse response=request.            GetResponse (); using(MemoryStream ms =NewMemoryStream ()) {                using(Stream stream =Response. GetResponseStream ()) {intREADC; byte[] buffer =New byte[1024x768];  while((READC = stream.) Read (Buffer,0, buffer. Length)) >0) {Ms. Write (Buffer,0, READC); }                }                returnencode. GetString (Ms.            ToArray ()); }} NameValueCollection Parseurlparameters (stringstr_params) {NameValueCollection NC=NewNameValueCollection (); foreach(stringPinchStr_params. Split ('&'))            {                string[] p_s = P.split ('='); nc. ADD (p_s[0], p_s[1]); }            returnNC; }        protected voidPage_Load (Objectsender, EventArgs e) {            //callback address after successful authorization            stringRedirect_uri = configurationmanager.appsettings["Redirect_uri"]; //AppID assigned to an app            stringclient_id = configurationmanager.appsettings["client_id"]; //Appkey assigned to a Web site            stringClient_secret = configurationmanager.appsettings["Client_secret"]; //User's OpenID            stringStropenid = request.querystring["OpenID"] ??string.            Empty; if(Stropenid.length <=0)            {                //STEP1: Get authorization Code                stringCode = request.querystring["Code"]; if(string. IsNullOrEmpty (code)) {//The state parameter is used to prevent csrf attacks, and callbacks are returned as they were after successful authorization.session[" State"] = Generaterndnonce ();//MD5 (Uniqid (rand (), TRUE));                     stringAuthorize_uri =string. Format ("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={0}&redirect_uri={1}& STATE={2}", client_id, Server.URLEncode (Redirect_uri), session[" State"]);                Response.Redirect (Authorize_uri); }                //STEP2: Get access Token by authorization code                if(request[" State"]. ToString (). Equals (session[" State"]. ToString ())) {//Parse Access_token return package                    stringToken_uri =string. Format ("Https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id={0}&client_secret={1} &CODE={2}&REDIRECT_URI={3}", client_id, Client_secret, Code, Redirect_uri); stringAccesstoken =file_get_contents (Token_uri, Encoding.UTF8); NameValueCollection PS=parseurlparameters (Accesstoken); stringAccess_token = ps["Access_token"]; stringexpires_in = ps["expires_in"]; stringRefresh_token = ps["Refresh_token"]; //Parse OpenID return package                    stringMe_uri =string. Format ("https://graph.qq.com/oauth2.0/me?access_token={0}", Access_token); stringcallback =file_get_contents (Me_uri, Encoding.UTF8); if(Callback. Contains ("Callback"))                    {                        intLpos = callback. IndexOf ("("); intRpoS = callback. IndexOf (")"); Callback= callback. Substring (Lpos +1, Rpos-lpos-1); } jobject jobject=Jobject.parse (callback); stringOpenID = jobject["OpenID"].                    ToString (); //STEP4: Get user information through Access_token,appid,openid                    stringGet_user_info_uri =string. Format ("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", Access_token, client_id, OpenID); stringUser_info =file_get_contents (Get_user_info_uri, Encoding.UTF8); Jobject=Jobject.parse (User_info); session["Nickname"] = jobject["Nickname"].                    ToString (); session["figureurl_qq_2"] = jobject["figureurl_qq_2"].                    ToString (); stringSQL =string. Format ("SELECT * from _users WHERE openid= ' {0} '", OpenID); DataTable DT=Sqlserver.select (SQL); if(dt. Rows.Count <=0) {SQL=string. Format ("INSERT into _users ([Nickname],[openid]) VALUES (' {0} ', ' {1} ')", session["Nickname"], OpenID);                    Sqlserver.execute (SQL); }                    //Authorize and JumpFormsauthentication.setauthcookie (OpenID,false); Response.Redirect ("index.aspx"); }            }        }    }}
View Code

How to integrate QQ login function with ASP

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.