Exemplo n.º 1
0
        public string Fetch(string code, string node)
        {
            string jsonStr = string.Empty;

            try {
                string postData = "code=" + code + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(this.RedirectUri) + "&client_id=" + ClientId + "&client_secret=" + ClientSecret + "&grant_type=authorization_code";
                Web_Request             = WebRequest.Create(googleApiUrl + "token?" + postData);
                Web_Request.Method      = "POST";
                Web_Request.ContentType = "application/x-www-form-urlencoded";

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                Web_Request.ContentLength = byteArray.Length;

                using (Stream dataStream = Web_Request.GetRequestStream()) {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }

                GoogleToken token = new GoogleToken();

                using (Web_Response = Web_Request.GetResponse()) {
                    using (Stream stream = Web_Response.GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream);
                        token = new JavaScriptSerializer().Deserialize <GoogleToken>(reader.ReadToEnd());
                    }
                }

                jsonStr = GetUserInfo(token);
            }
            catch { }

            return(jsonStr);
        }
        /// <summary>
        /// 检查用户是否有该Action执行的操作权限
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)//验证WebApi的参数与特性是否有效
            {
                if (actionContext.ModelState.FirstOrDefault(item => item.Value.Errors.Count > 0).Value.Errors.Count > 0)
                {
                    actionContext.Response = Web_Response.ResponseResult(
                        new ResponseModel()
                    {
                        StatusCode = HttpStatusCode.OK, ErrorMsg = actionContext.ModelState.FirstOrDefault(item => item.Value.Errors.Count > 0).Value.Errors.FirstOrDefault().ErrorMessage
                    });
                }
            }
            if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)//获取Authorization值
            {
                System.Net.Http.Headers.AuthenticationHeaderValue authValue = new System.Net.Http.Headers.AuthenticationHeaderValue(HttpContext.Current.User.Identity.Name, HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
                actionContext.Request.Headers.Authorization = authValue;
            }
            //http://www.faceye.net/search/102356.html
            //检验用户ticket信息,用户ticket信息来自调用发起方
            var authorization = actionContext.Request.Headers.Authorization;

            if ((authorization != null) && (authorization.Parameter != null))
            {
                //解密用户ticket,并校验用户名密码是否匹配
                var encryptTicket = authorization.Parameter;
                if (ValidateUserTicket(encryptTicket))
                {
                    base.OnActionExecuting(actionContext);
                }
                else
                {
                    actionContext.Response = Web_Response.ResponseResult(
                        new ResponseModel()
                    {
                        StatusCode = HttpStatusCode.Unauthorized, ErrorMsg = "登录失效"
                    });
                }
            }
            else
            {
                //如果请求Header不包含ticket,则判断是否是匿名调用
                var  attr        = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>();
                bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);

                //是匿名用户,则继续执行;非匿名用户,抛出“未授权访问”信息
                if (isAnonymous)
                {
                    base.OnActionExecuting(actionContext);
                }
                else
                {
                    actionContext.Response = Web_Response.ResponseResult(
                        new ResponseModel()
                    {
                        StatusCode = HttpStatusCode.Unauthorized, ErrorMsg = "未授权访问"
                    });
                }
            }
        }
 public override void OnException(HttpActionExecutedContext context)
 {
     try
     {
         //日志路径
         string        path   = HttpContext.Current.Server.MapPath("/Logs/WebApi/" + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + ".txt");
         Exception     ex     = context.Exception;
         StringBuilder errMsg = new StringBuilder();
         errMsg.Append("请求地址:" + context.Request.RequestUri + "\r\n");
         errMsg.Append("请求时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
         errMsg.Append("请求IP:" + Common.IPHelper.GetIP() + "\r\n");
         errMsg.Append("错误消息:" + ex.Message + "\r\n");
         errMsg.Append("错误方法:" + ex.TargetSite.ToString() + "\r\n");
         errMsg.Append("错误对象:" + ex.Source + "\r\n");
         errMsg.Append("栈堆信息:" + ex.StackTrace + "\r\n");
         Common.FileHelper.WriteLog(path, true, errMsg.ToString());
     }
     finally
     {
         context.Response = Web_Response.ResponseResult(
             new ResponseModel()
         {
             StatusCode = HttpStatusCode.InternalServerError, ErrorMsg = "服务器响应失败,错误原因:" + context.Exception.Message
         });
     }
 }
Exemplo n.º 4
0
        private string GetUserInfo(GoogleToken token)
        {
            string jsonStr = string.Empty;

            if (!string.IsNullOrEmpty(token.access_token))
            {
                Web_Request = WebRequest.Create("https://www.googleapis.com/plus/v1/people/me?access_token=" + token.access_token);

                using (Web_Response = Web_Request.GetResponse()) {
                    using (Stream stream = Web_Response.GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream);
                        jsonStr = reader.ReadToEnd();
                    }
                }
            }

            return(jsonStr);
        }
Exemplo n.º 5
0
        private void DeletePermissions(string node)
        {
            if (!string.IsNullOrEmpty(AccessToken))
            {
                Web_Request        = WebRequest.Create(graphApiUrl + node + "/permissions?access_token=" + AccessToken);
                Web_Request.Method = "DELETE";

                using (Web_Response = Web_Request.GetResponse()) {
                    using (Stream stream = Web_Response.GetResponseStream()) {
                        StreamReader        reader = new StreamReader(stream);
                        FaceBookPermissions faceBookPermisssions = new JavaScriptSerializer().Deserialize <FaceBookPermissions>(reader.ReadToEnd());

                        if (faceBookPermisssions != null && faceBookPermisssions.success.ToLower() == "true")
                        {
                            AccessToken = string.Empty;
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        public String getRespones(HttpWebRequest Web_Request)
        {
            HttpWebResponse Web_Response;
            string          html;

            try
            {
                Web_Response = (HttpWebResponse)Web_Request.GetResponse();
            }
            catch (Exception)
            {
                return(CONN_ERR);
            }

            logger.Info("本次获取的Cookie:" + GetCookieIndexCookieKey(_cookie, "JSESSIONID"));
            if (Web_Response.ContentEncoding.ToLower() == "gzip")  // 如果使用了GZip则先解压
            {
                using (Stream Stream_Receive = Web_Response.GetResponseStream())
                {
                    using (var Zip_Stream = new GZipStream(Stream_Receive, CompressionMode.Decompress))
                    {
                        using (StreamReader Stream_Reader = new StreamReader(Zip_Stream, Encoding.UTF8))
                        {
                            html = Stream_Reader.ReadToEnd();
                        }
                    }
                }
            }
            else
            {
                using (Stream Stream_Receive = Web_Response.GetResponseStream())
                {
                    using (StreamReader Stream_Reader = new StreamReader(Stream_Receive, Encoding.UTF8))
                    {
                        html = Stream_Reader.ReadToEnd();
                    }
                }
            }
            logger.Info("本次获取的html:" + html);
            return(html);
        }
Exemplo n.º 7
0
        private string GetUserInfo(string node)
        {
            string jsonStr = string.Empty;

            if (!string.IsNullOrEmpty(AccessToken))
            {
                try {
                    Web_Request        = WebRequest.Create(graphApiUrl + node + "?access_token=" + AccessToken);
                    Web_Request.Method = "GET";

                    using (Web_Response = Web_Request.GetResponse()) {
                        using (Stream stream = Web_Response.GetResponseStream()) {
                            StreamReader reader = new StreamReader(stream);
                            jsonStr = reader.ReadToEnd();
                        }
                    }

                    DeletePermissions(node);
                }
                catch { }
            }

            return(jsonStr);
        }
Exemplo n.º 8
0
        public string Fetch(string code, string node)
        {
            try {
                Web_Request        = WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=" + API_Key + "&redirect_uri=" + this.Redirect_Url + "&client_secret=" + API_Secret + "&code=" + code);
                Web_Request.Method = "GET";

                using (Web_Response = Web_Request.GetResponse()) {
                    using (Stream stream = Web_Response.GetResponseStream()) {
                        StreamReader reader          = new StreamReader(stream);
                        string       tempAccessToken = reader.ReadToEnd();
                        try {
                            FacebookAccessTokenRequest facebookAccess = new JavaScriptSerializer().Deserialize <FacebookAccessTokenRequest>(tempAccessToken);
                            AccessToken = facebookAccess.access_token;
                        }
                        catch {
                            AccessToken = tempAccessToken;
                        }
                    }
                }
            }
            catch { }

            return(GetUserInfo(node));
        }