ASP.NET 网站如何集成QQ登录功能

2018-08-3117:37:24来源:云起点 评论 1,001 views

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Data;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Scratchline.Database;
using System.Web.Security;

namespace Scratchline.CN
{
public partial class login_qq : System.Web.UI.Page
{
private static Random RndSeed = new Random();

    public string GenerateRndNonce()
    {
        return (RndSeed.Next(1, 0xf423f).ToString("000000") + RndSeed.Next(1, 0xf423f).ToString("000000"));
    }

    public string file_get_contents(string url, Encoding encode)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        WebResponse response = request.GetResponse();
        using (MemoryStream ms = new MemoryStream())
        {
            using (Stream stream = response.GetResponseStream())
            {
                int readc;
                byte[] buffer = new byte[1024];
                while ((readc = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, readc);
                }
            }
            return encode.GetString(ms.ToArray());
        }
    }
    NameValueCollection ParseUrlParameters(string str_params)
    {
        NameValueCollection nc = new NameValueCollection();
        foreach (string p in str_params.Split('&'))
        {
            string[] p_s = p.Split('=');
            nc.Add(p_s[0], p_s[1]);
        }
        return nc;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // 成功授权后的回调地址
        string redirect_uri = ConfigurationManager.AppSettings["redirect_uri"];
        // 分配给应用的appid
        string client_id = ConfigurationManager.AppSettings["client_id"];
        // 分配给网站的appkey
        string client_secret = ConfigurationManager.AppSettings["client_secret"];
        // 用户的OpenID
        string strOpenId = Request.QueryString["openid"] ?? string.Empty;

        if (strOpenId.Length <= 0)
        {
            //Step1:获取Authorization Code  
            string code = Request.QueryString["code"];
            if (string.IsNullOrEmpty(code))
            {
                //state参数用于防止CSRF攻击,成功授权后回调时会原样带回  
                Session["state"] = GenerateRndNonce();//md5(uniqid(rand(), TRUE));   
                string authorize_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:通过Authorization Code获取Access Token  
            if (Request["state"].ToString().Equals(Session["state"].ToString()))
            {
                // 解析access_token返回包
                string token_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);
                string accesstoken = file_get_contents(token_uri, Encoding.UTF8);
                NameValueCollection ps = ParseUrlParameters(accesstoken);
                string access_token = ps["access_token"];
                string expires_in = ps["expires_in"];
                string refresh_token = ps["refresh_token"];

                // 解析OpenID返回包
                string me_uri = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", access_token);
                string callback = file_get_contents(me_uri, Encoding.UTF8);
                if (callback.Contains("callback"))
                {
                    int lpos = callback.IndexOf("(");
                    int rpos = callback.IndexOf(")");
                    callback = callback.Substring(lpos + 1, rpos - lpos - 1);
                }
                JObject jobject = JObject.Parse(callback);
                string openid = jobject["openid"].ToString();

                //Step4:通过access_token,appid,openid获得用户信息
                string get_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);
                string user_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();


                string SQL = 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);
                }
                // 授权并跳转
                FormsAuthentication.SetAuthCookie(openid, false);
                Response.Redirect("index.aspx");
            }
        }
    }
}

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: