Пример #1
0
		public static async Task SendEventHubEventAsync(TemperatureData temperatureData)
		{
			HttpClient client = new HttpClient();

			client.DefaultRequestHeaders.Clear();

			var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue(
				"SharedAccessSignature", SAS);
			client.DefaultRequestHeaders.Authorization = authHeader;

			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TemperatureData));
			string body = string.Empty;
			using (MemoryStream ms = new MemoryStream())
			using (StreamReader sr = new StreamReader(ms))
			{
				serializer.WriteObject(ms, temperatureData);
				ms.Seek(0, SeekOrigin.Begin);
				body = sr.ReadToEnd();
			}
			StringContent content = new StringContent(body, Encoding.UTF8);
			client.BaseAddress = new Uri(BaseUri);

			//await client.PostAsync(ServiceUri, content);

			client.Dispose();
		}
 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Exception is UnauthorizedAccessException)
     {
         string resource = ConfigurationManager.AppSettings["ida:Resource"];
         string redirectUri = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/Home/SPA";
         string authorizationUrl = OAuthController.GetAuthorizationUrl(resource, new Uri(redirectUri));
         actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
         System.Net.Http.Headers.AuthenticationHeaderValue realm = new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", "realm=\"" + authorizationUrl + "\"");
         actionExecutedContext.Response.Headers.WwwAuthenticate.Add(realm);
     }
 }
Пример #3
0
        public IEdmModel LoadModel(Uri realm)
        {
            using (HttpClient client = new HttpClient())
            {
                var header = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetRawToken());
                client.DefaultRequestHeaders.Authorization = header;

                Console.WriteLine("\t{0} {1}", "GET", realm.ToString() + "$metadata");

                HttpResponseMessage response = client.GetAsync(realm.ToString() + "$metadata").Result;
                var stream = response.Content.ReadAsStreamAsync().Result;
                using (var reader = XmlReader.Create(stream))
                {
                    IEdmModel model = EdmxReader.Parse(reader);
                    _modelLoadCompleteEvent.Set();
                    return model;
                }
            }
        }
Пример #4
0
		public async Task<ActionResult> Bluemix(string PerguntaEntrada)
		{

			Bluemix bluemx = new Bluemix();
			AtributosBluemix atributosBlue = new AtributosBluemix();

			

			using (HttpClient http = new HttpClient())
			{

				string url = "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/0235B6x12-nlc-599/classify?text=" + PerguntaEntrada;

				var obj = new { username = "******", password = "******" };

				var byteArray = Encoding.ASCII.GetBytes(String.Concat(obj.username, ":", obj.password));

				var header = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

				http.DefaultRequestHeaders.Authorization = header;

				var a = await http.GetStringAsync(url);

				string[] vSplit = a.Split('\n');

				atributosBlue.SaidaResposta = vSplit[4].Replace("top_class", "");
				atributosBlue.SaidaResposta = atributosBlue.SaidaResposta.Replace(":", "");
				atributosBlue.SaidaResposta = atributosBlue.SaidaResposta.Replace(",", "");
				atributosBlue.SaidaResposta = atributosBlue.SaidaResposta.Replace("\\", "");
				atributosBlue.SaidaResposta = atributosBlue.SaidaResposta.Replace("\"", "");


				atributosBlue.SaidaResposta = bluemx.RetornaRespostaFaq(atributosBlue.SaidaResposta.Trim());

				return View("Bluemix", atributosBlue);


			}


		}
        /// <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 = "未授权访问" });

            }
        }
Пример #6
0
        protected Session RequireApiKey()
        {
            IEnumerable<string> apiKeys;
            ErrorMessage error;
            if (this.Request.Headers.TryGetValues("BoardApiKey", out apiKeys))
            {
                var key = apiKeys.FirstOrDefault();
                if (key != null)
                {
                    Session session;
                    if (Models.Session.TryGetByKey(key, out session))
                    {
                        return session;
                    }
                    else
                    {
                        error = ErrorMessage.InvalidApiKey;
                    }
                }
                else
                {
                    error = ErrorMessage.NoApiKey;
                }

            }
            else
            {
                error = ErrorMessage.NoApiKey;
            }
            var response = Request.CreateResponse(HttpStatusCode.Unauthorized, error);

            var header = new System.Net.Http.Headers.AuthenticationHeaderValue("BoardApiKeyAuth", "realm=\"BoardGameWeb\"");
            response.Headers.WwwAuthenticate.Add(header);

            throw new HttpResponseException(response);
        }