Ejemplo n.º 1
0
        /// <summary>
        /// Used by App.net oAuth process to retrieve tokens.
        /// </summary>
        /// <param name="code"></param>
        /// <param name="returl"></param>
        /// <returns></returns>
        public void TokenGet(string code, string returl)
        {
            string url = OAUTH_ACCESS_TOKEN;

            string json = AuthUtilities.WebRequest(AuthUtilities.Method.POST, url,
                                                   "client_id=" + HttpUtility.UrlEncode(ConfigurationManager.AppSettings["appdotnet_clientid"].ToString())
                                                   + "&client_secret=" + HttpUtility.UrlEncode(ConfigurationManager.AppSettings["appdotnet_clientsecret"].ToString())
                                                   + "&grant_type=authorization_code"
                                                   + "&redirect_uri=" + HttpUtility.UrlEncode(returl)
                                                   + "&code=" + HttpUtility.UrlEncode(code)
                                                   );
            AppDotNetAccessToken token = Json.Deserialise <AppDotNetAccessToken>(json);

            this.access_token = token.access_token;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Used by Google oAuth process to retrieve tokens.
        /// </summary>
        /// <param name="code"></param>
        /// <param name="refresh_token"></param>
        /// <param name="returl"></param>
        /// <returns></returns>
        public static GoogleTokens GoogleTokensGet(string code, string refresh_token, string returl)
        {
            string grant_type            = "authorization_code";
            string code_or_refresh_token = "code=" + System.Web.HttpUtility.UrlEncode(code);

            if (refresh_token != null)
            {
                grant_type            = "refresh_token";
                code_or_refresh_token = "refresh_token=" + System.Web.HttpUtility.UrlEncode(refresh_token);
            }

            string json = AuthUtilities.WebRequest(AuthUtilities.Method.POST, "https://accounts.google.com/o/oauth2/token",
                                                   code_or_refresh_token
                                                   + "&client_id=" + ConfigurationManager.AppSettings["google_clientid"].ToString()
                                                   + "&client_secret=" + ConfigurationManager.AppSettings["google_clientsecret"].ToString()
                                                   + "&redirect_uri=" + System.Web.HttpUtility.UrlEncode(returl)
                                                   + "&grant_type=" + grant_type
                                                   );

            return(Json.Deserialise <GoogleTokens>(json));
        }
Ejemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Twitter
            //Twitter oAuth Start
            if (Request["twitterauth"] != null && Request["twitterauth"] == "true")
            {
                oAuthTwitter oAuth = new oAuthTwitter();
                oAuth.CallBackUrl = Request.Url.AbsoluteUri.Replace("twitterauth=true", "twitterauth=false");
                //Redirect the user to Twitter for authorization.
                Response.Redirect(oAuth.AuthorizationLinkGet());
            }
            //Twitter Return
            if (Request["twitterauth"] != null && Request["twitterauth"] == "false")
            {
                oAuthTwitter oAuth = new oAuthTwitter();
                //Get the access token and secret.
                oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
                if (oAuth.TokenSecret.Length > 0)
                {
                    //STORE THESE TOKENS FOR LATER CALLS
                    //Subsequent calls can be made without the Twitter login screen.
                    //Move this code outside of this auth process if you already have the tokens.
                    //
                    //Example:
                    //oAuthTwitter oAuth = new oAuthTwitter();
                    //oAuth.Token = Session["token"];
                    //oAuth.TokenSecret = Session["token_secret"];
                    //Then make the following Twitter call.

                    //SAMPLE TWITTER API CALL
                    string      url  = "https://api.twitter.com/1.1/account/verify_credentials.json";
                    TwitterUser user = Json.Deserialise <TwitterUser>(oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, url, String.Empty));

                    if (user.id.Length > 0)
                    {
                        UserData userData = new UserData();
                        userData.id          = user.id;
                        userData.username    = user.screen_name;
                        userData.name        = user.name;
                        userData.serviceType = "twitter";
                        userData.imageUrl    = user.profile_image_url;
                        AuthSuccess(userData);
                    }

                    //POST Test
                    //url = "https://api.twitter.com/1.1/statuses/update.json";
                    //xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode("Hello @swhitley - Testing the .NET oAuth API"));
                    Response.Clear();
                    Response.Write("<script>window.opener.location.reload();window.close();</script>");
                }
            }
            #endregion

            #region Google
            //Google oAuth Start
            if (Request["googleauth"] != null && Request["googleauth"] == "true")
            {
                string returl = Request.Url.AbsoluteUri.Replace("googleauth=true", "googleauth=false");
                string url    = "https://accounts.google.com/o/oauth2/auth?client_id=" + System.Web.HttpUtility.UrlEncode(ConfigurationManager.AppSettings["google_clientid"].ToString()) + "&redirect_uri=" + System.Web.HttpUtility.UrlEncode(returl)
                                + "&scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo#email") + "&response_type=code";
                Response.Redirect(url);
            }
            //Google Return
            if (Request["googleauth"] != null && Request["googleauth"] == "false")
            {
                string       code   = Request["code"];
                string       returl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("&code="));
                GoogleTokens tokens = GoogleAuth.GoogleTokensGet(code, null, returl);

                //STORE THESE TOKENS FOR LATER CALLS
                //tokens.access_token - tokens.refresh_token

                //SAMPLE GOOGLE API CALL
                //Set the access token in the header.  It expires, so prepare to use the refresh token to get a new access token (not shown).
                List <KeyValuePair <string, string> > headers = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("Authorization", "OAuth " + tokens.access_token)
                };
                string     url  = "https://www.googleapis.com/userinfo/email?alt=json";
                GoogleData user = Json.Deserialise <GoogleData>(AuthUtilities.WebRequest(AuthUtilities.Method.GET, url, "", headers));

                if (user.data != null && user.data.email.Length > 0)
                {
                    UserData userData = new UserData();
                    userData.username    = user.data.email;
                    userData.serviceType = "google";
                    AuthSuccess(userData);
                }

                Response.Clear();
                Response.Write("<script>window.opener.location.reload();window.close();</script>");
            }
            #endregion

            #region Facebook
            //Facebook Return
            if (Request.Params["fbsr_" + ConfigurationManager.AppSettings["facebook_appid"].ToString()] != null && Request["facebookauth"] == "false")
            {
                string signed_request = Request["fbsr_" + ConfigurationManager.AppSettings["facebook_appid"]].ToString().Replace("\"", "");

                //Parse the signed_request;
                FacebookAuthRequest req = FacebookAuth.ParseSignedRequest(signed_request, ConfigurationManager.AppSettings["facebook_appsecret"]);

                //Get the Access Token
                string url = "https://graph.facebook.com/oauth/access_token?client_id=" + Server.UrlEncode(ConfigurationManager.AppSettings["facebook_appid"].ToString()) + "&redirect_uri=&client_secret=" + Server.UrlEncode(ConfigurationManager.AppSettings["facebook_appsecret"].ToString()) + "&code=" + Server.UrlEncode(req.code);
                NameValueCollection ret = HttpUtility.ParseQueryString(AuthUtilities.WebRequest(AuthUtilities.Method.GET, url, ""));

                string access_token = "";
                foreach (string key in ret.Keys)
                {
                    if (key == "access_token")
                    {
                        access_token = ret[key].ToString();
                    }
                }

                //STORE THIS TOKEN FOR LATER CALLS
                //access_token

                //SAMPLE FACEBOOK API CALL
                url = "https://graph.facebook.com/me?access_token=%%access_token%%";
                url = url.Replace("%%access_token%%", access_token);
                FacebookMe fb_me = Json.Deserialise <FacebookMe>(AuthUtilities.WebRequest(AuthUtilities.Method.GET, url, ""));

                //Validation -- uid and accesstoken reference same id.
                if (req.user_id == fb_me.id)
                {
                    if (fb_me.username.Length == 0)
                    {
                        fb_me.username = fb_me.name;
                    }
                    UserData userData = new UserData();
                    userData.id          = fb_me.id;
                    userData.username    = fb_me.username;
                    userData.serviceType = "facebook";
                    userData.name        = fb_me.name;

                    AuthSuccess(userData);
                }
                Response.Clear();
                Response.Write("<script>location.href = '../';</script>");
            }
            if (Request["facebookauth"] == "false" && !User.Identity.IsAuthenticated)
            {
                Response.Clear();
                Response.Write("<script>location.href = '../';</script>");
            }
            #endregion

            #region LinkedIn
            //LinkedIn Return
            if (Request.Cookies["linkedin_oauth_" + ConfigurationManager.AppSettings["linkedin_consumer_key"].ToString()] != null)
            {
                //Cookie Json object
                LinkedIn_oAuth_Cookie cookie = Json.Deserialise <LinkedIn_oAuth_Cookie>(Server.UrlDecode(Request.Cookies["linkedin_oauth_" + ConfigurationManager.AppSettings["linkedin_consumer_key"].ToString()].Value));

                //Verify the signature
                oAuthLinkedIn oAuthLi = new oAuthLinkedIn();
                string        sigBase = cookie.access_token + cookie.member_id;

                HMACSHA1 hmacsha1 = new HMACSHA1();
                hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}", oAuthLi.UrlEncode(ConfigurationManager.AppSettings["linkedin_consumer_secret"])));

                string sig = oAuthLi.GenerateSignatureUsingHash(sigBase, hmacsha1);

                //Retrieve the access token.
                if (sig == cookie.signature)
                {
                    string   response     = oAuthLi.oAuthWebRequest(oAuthLinkedIn.Method.POST, oAuthLi.ACCESS_TOKEN + "?xoauth_oauth2_access_token=" + oAuthLi.UrlEncode(cookie.access_token), "");
                    string[] tokens       = response.Split('&');
                    string   token        = tokens[0].Split('=')[1];
                    string   token_secret = tokens[1].Split('=')[1];

                    //STORE THESE TOKENS FOR LATER CALLS
                    oAuthLi.Token       = token;
                    oAuthLi.TokenSecret = token_secret;

                    //SAMPLE LINKEDIN API CALL
                    string url = "http://api.linkedin.com/v1/people/id=%%id%%:("
                                 + "id"
                                 + ",first-name"
                                 + ",last-name"
                                 + ")";
                    url = url.Replace("%%id%%", cookie.member_id);
                    string xml = oAuthLi.oAuthWebRequest(oAuthLinkedIn.Method.GET, url, "");

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xml);
                    string id   = "";
                    string name = "";
                    foreach (XmlElement person in xmlDoc.GetElementsByTagName("person"))
                    {
                        if (person["id"] != null)
                        {
                            id = person["id"].InnerText;
                        }
                        if (person["first-name"] != null)
                        {
                            name = person["first-name"].InnerText;
                        }
                        if (person["last-name"] != null)
                        {
                            if (name.Length > 0)
                            {
                                name += " ";
                            }
                            name += person["last-name"].InnerText;
                        }
                    }

                    if (id.Length > 0)
                    {
                        UserData userData = new UserData();
                        userData.id          = id;
                        userData.username    = name;
                        userData.name        = name;
                        userData.serviceType = "linkedin";
                        AuthSuccess(userData);
                    }

                    Response.Clear();
                    Response.Write(Request["callback"].ToString() + "()");
                }
            }
            #endregion

            #region Auth.Net
            //App.net oAuth Start
            if (Request["appdotnetauth"] != null && Request["appdotnetauth"] == "true")
            {
                //TODO: Customize this list for your needs.
                string scope = (
                    AppDotNetAuth.Scope.stream
                    | AppDotNetAuth.Scope.follow
                    | AppDotNetAuth.Scope.write_post
                    | AppDotNetAuth.Scope.messages
                    | AppDotNetAuth.Scope.export
                    ).ToString().Replace(",", "");

                //Redirect the user to App.net for authorization.
                Response.Redirect(AppDotNetAuth.AuthorizationLinkGet(scope, Request.Url.AbsoluteUri.Replace("appdotnetauth=true", "appdotnetauth=false")));
            }
            //App.net Return
            if (Request["appdotnetauth"] != null && Request["appdotnetauth"] == "false")
            {
                if (Request["code"] != null && Request["state"] != null)
                {
                    AppDotNetAuth oAuth = new AppDotNetAuth();

                    //Get the access token.
                    oAuth.TokenGet(Request["code"].ToString(), Request["state"].ToString());

                    if (oAuth.access_token.Length > 0)
                    {
                        //STORE THE ACCESS TOKEN FOR LATER CALLS
                        //Subsequent calls can be made without the App.net login screen.
                        //Move this code outside of this auth process if you already have the tokens.
                        //
                        //Example:
                        //AppDotNetAuth oAuth = new AppDotNetAuth();
                        //oAuth.access_token = Session["access_token"];
                        //Then make the following App.net call.

                        ////SAMPLE App.net API CALL
                        string url = AppDotNetAuth.USER.Replace("[user_id]", "me");

                        AppDotNetUser user = Json.Deserialise <AppDotNetUserWrapper>(AuthUtilities.WebRequest(AuthUtilities.Method.GET, url, String.Empty, oAuth.AuthHeader())).data;

                        if (user.id.Length > 0)
                        {
                            UserData userData = new UserData();
                            userData.id          = user.id;
                            userData.username    = user.username;
                            userData.name        = user.name;
                            userData.serviceType = "appdotnet";
                            AuthSuccess(userData);
                        }

                        //POST Test
                        //url = AppDotNetAuth.WRITE_POST;
                        //string json = AuthUtilities.WebRequest(AuthUtilities.Method.POST, url, "text=" + HttpUtility.UrlEncode("Hello @swhitley - Testing the .NET oAuth API"), oAuth.AuthHeader());

                        Response.Clear();
                        Response.Write("<script>window.opener.location.reload();window.close();</script>");
                    }
                }
            }
            #endregion



            //TODO: Add Error Handling
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post (querystring format)</param>
        /// <returns>The web server response.</returns>
        public int oAuthWebRequest(Method method, string url, string postData, out string response)
        {
            string outUrl      = "";
            string querystring = "";

            response = "";

            //Setup postData for signing.
            //Add the postData to the querystring.
            if (method == Method.POST || method == Method.DELETE)
            {
                if (postData.Length > 0)
                {
                    //Decode the parameters and re-encode using the oAuth UrlEncode method.
                    NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                    postData = "";
                    foreach (string key in qs.AllKeys)
                    {
                        if (postData.Length > 0)
                        {
                            postData += "&";
                        }
                        qs[key]   = HttpUtility.UrlDecode(qs[key]);
                        qs[key]   = this.UrlEncode(qs[key]);
                        postData += key + "=" + qs[key];
                    }
                    if (url.IndexOf("?") > 0)
                    {
                        url += "&";
                    }
                    else
                    {
                        url += "?";
                    }
                    url += postData;
                }
            }

            Uri uri = new Uri(url);

            string nonce     = this.GenerateNonce();
            string timeStamp = this.GenerateTimeStamp();

            //Generate Signature
            string sig = this.GenerateSignature(uri,
                                                this.ConsumerKey,
                                                this.ConsumerSecret,
                                                this.Token,
                                                this.TokenSecret,
                                                this.CallBackUrl,
                                                this.OAuthVerifier,
                                                method.ToString(),
                                                timeStamp,
                                                nonce,
                                                out outUrl,
                                                out querystring);

            querystring += "&oauth_signature=" + this.UrlEncode(sig);

            //Convert the querystring to postData
            if (method == Method.POST || method == Method.DELETE)
            {
                postData    = querystring;
                querystring = "";
            }

            if (querystring.Length > 0)
            {
                outUrl += "?";
            }

            int status = AuthUtilities.WebRequest((AuthUtilities.Method)method, outUrl + querystring, postData, out response);

            return(status);
        }