2012年11月5日 星期一

OAuth 2.0

1) Register your application into Google to have client ID & secrete key
   
2) Login here : https://code.google.com/apis/console/
  
3) App Access : Create ID

4) Web.Config add :


5) xxx.cs
        public string Email_address = "";
        public string Google_ID = "";
        public string firstName = "";
        public string LastName = "";
        public string Client_ID = "";
        public string Return_url = "";
        public string Picture = "";
        protected void Page_Load(object sender, EventArgs e) {
            if (!this.IsPostBack) {
                Client_ID = ConfigurationSettings.AppSettings["google_clientId"].ToString();
                Return_url = ConfigurationSettings.AppSettings["google_RedirectUrl"].ToString();
            }
        
                if (Request.QueryString["access_token"] != null) {
                    String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + Request.QueryString["access_token"].ToString();
                    WebClient webClient = new WebClient();
                    Stream stream = webClient.OpenRead(URI);
                    string b;
                    using (StreamReader br = new StreamReader(stream)) {
                        b = br.ReadToEnd();
                    }
                    b = b.Replace("id", "").Replace("email", "");
                    b = b.Replace("given_name", "");
                    b = b.Replace("family_name", "").Replace("link", "").Replace("picture", "");
                    b = b.Replace("gender", "").Replace("locale", "").Replace(":", "");
                    b = b.Replace("\"", "").Replace("name", "").Replace("{", "").Replace("}", "");
                    Array ar = b.Split(",".ToCharArray());
                    for (int p = 0; p < ar.Length; p++) {
                        ar.SetValue(ar.GetValue(p).ToString().Trim(), p);
                    }
                    Google_ID = ar.GetValue(0).ToString();
                    Email_address = ar.GetValue(1).ToString();
                   
                    firstName = ar.GetValue(4).ToString();
                    LastName = ar.GetValue(5).ToString();
                    Picture = ar.GetValue(7).ToString();
                }

        }


ref 1:https://developers.google.com/accounts/docs/OAuth2#basicsteps