static string getJsonData(string Url) { string result = string.Empty; HttpWebRequest http = (HttpWebRequest)WebRequest.Create(Url); if (true) { http.ServerCertificateValidationCallback += delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); // **** Always accept }; } var byteArray = Encoding.ASCII.GetBytes($"{CloudConfigurationManager.GetSetting(Settings.APPKEY_RESTENDPOINT_UID)}:{CloudConfigurationManager.GetSetting(Settings.APPKEY_RESTENDPOINT_PWD)}"); string basicAuthValue = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)).ToString(); http.Headers.Add(HttpRequestHeader.Authorization, basicAuthValue); using (WebResponse response = http.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader sr = new StreamReader(stream); result = sr.ReadToEnd(); Console.WriteLine(result + "..."); } } return(result); }
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 MailchimpClient(HttpClient httpClient, IOptions <ExternalClientsConfig> externalClientsConfig, ILogger <MailchimpClient> logger) { _logger = logger; _httpClient = httpClient; var apiKey = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"conner:{externalClientsConfig.Value.MailchimpApi.ApiKey}")); _logger.LogInformation($"Setting apiKey: {apiKey}"); var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey); _httpClient.DefaultRequestHeaders.Authorization = authHeader; _httpClient.BaseAddress = new Uri(externalClientsConfig.Value.MailchimpApi.BaseUrl); _logger.LogInformation($"Setting baseAddress: {_httpClient.BaseAddress}"); _allDayChaperonesEndpoint = externalClientsConfig.Value.MailchimpApi.AllDayChaperonesEndpoint; _eveningChaperonesEndpoint = externalClientsConfig.Value.MailchimpApi.EveningChaperonesEndpoint; _lebanonChaperonesEndpoint = externalClientsConfig.Value.MailchimpApi.LebanonChaperonesEndpoint; _driversEndpoint = externalClientsConfig.Value.MailchimpApi.DriversEndpoint; _logger.LogInformation($"Setting allDayChaperones Endpoint: {_allDayChaperonesEndpoint}"); var contractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() }; _snakeCaseSerializer = new JsonSerializerSettings { ContractResolver = contractResolver, Formatting = Formatting.Indented }; }
public LicenseResolver(SpdxLicenseData spdxLicenseData, string githubUsername, string githubPassword) { _spdxLicenseData = spdxLicenseData; var byteArray = Encoding.ASCII.GetBytes(githubUsername + ":" + githubPassword); _authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); }
/// <summary> /// Get Token Id /// </summary> /// <param name="filterContext">AuthenticationHeaderValue</param> /// <devdoc> /// Developer Name - Arvind Kumar /// Date - 02-25-2015 /// </devdoc> private string ExtractToken(System.Net.Http.Headers.AuthenticationHeaderValue authHeader) { //Base 64 encoded string var token = authHeader.Parameter; return(token); }
public string ConvertCredentialValue(System.Net.Http.Headers.AuthenticationHeaderValue authHeader) { var rawCredential = authHeader.Parameter; var encodingValue = Encoding.GetEncoding("iso-8859-1"); return(encodingValue.GetString(Convert.FromBase64String(rawCredential))); }
/// <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 OnAuthorization(AuthorizationContext context) { System.Net.Http.Headers.AuthenticationHeaderValue authorizationHeader = context.HttpContext.Request.Headers.Authorization; // Check that the Authorization header is present in the HTTP request and that it is in the // format of "Authorization: Bearer <token>" if ((authorizationHeader == null) || (authorizationHeader.Scheme.CompareTo("Bearer") != 0) || (String.IsNullOrEmpty(authorizationHeader.Parameter))) { // return HTTP 401 Unauthorized } using (WebClient client = new WebClient()) { client.Headers.Add("Authorization", "Bearer " + authorizationHeader.Parameter); string userinfo = client.DownloadString("authURL/GetUserInfo"); CustomUser user = JsonConvert.DeserializeObject <CustomUser>(userinfo); if (!user.Roles == this.Roles) { // I recommend return HTTP 403 Forbidden here, not 401. At this point // the request has been authenticated via the bearer token, but the // authenticated client does not have sufficient roles to execute the // request, so they are forbidden from doing so. HTTP 401 Unauthorized // is a bit of a misnomer because the actual intention is to determine // whether or not the request is authenticated. HTTP 401 also implies // that the request should be tried again with credentials, but that // has already been done! } } }
private void ServiceAuthentication(System.Net.Http.Headers.AuthenticationHeaderValue auth, HttpCookieCollection cookieCollection, out int userId, out string apiKeyId) { userId = -1; apiKeyId = null; if (auth != null && (new string[] { "Basic", "Partner" }).Any(T => T.Equals(auth.Scheme, StringComparison.InvariantCultureIgnoreCase))) { string authValue = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter)); if (string.Compare(auth.Scheme, "Partner", StringComparison.OrdinalIgnoreCase) == 0) { apiKeyId = authValue; return; } string userEmail = authValue.Substring(0, authValue.IndexOf(':')); string userPassword = authValue.Substring(authValue.IndexOf(':') + 1); // get user-id Facade.WebAppFacade.UserDetailsFacade.AuthenticateUser(userEmail, userPassword, out userId); } else { string formsCookieName = cookieCollection[FormsAuthentication.FormsCookieName].Value; userId = int.Parse(FormsAuthentication.Decrypt(formsCookieName).Name); } }
public async static Task <bool> HayCnxSrv(string srv) { //return(await CrossConnectivity.Current.IsRemoteReachable(srv)); bool ret = false; try { using (HttpClient client = new HttpClient() { Timeout = System.TimeSpan.FromSeconds(5) }) { //------ Credenciales y SSL -------------------------- var byteArray = Encoding.ASCII.GetBytes(Settings.WebServiceUsr + ":" + Settings.WebServicePwd); var header = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Authorization = header; //------ Credenciales y SSL -------------------------- using (HttpResponseMessage response = await client.GetAsync(srv)) { ret = response.IsSuccessStatusCode; //200 = ok } } } catch { ret = false; //se cancela la Task } return(ret); }
/// <summary> /// This creates the authorization header. This is required, and must be built /// exactly following the instructions. This will return the authorization header /// for most storage service calls. /// Create a string of the message signature and then encrypt it. /// </summary> /// <param name="storageAccountName">The name of the storage account to use.</param> /// <param name="storageAccountKey">The access key for the storage account to be used.</param> /// <param name="now">Date/Time stamp for now.</param> /// <param name="httpRequestMessage">The HttpWebRequest that needs an auth header.</param> /// <param name="ifMatch">Provide an eTag, and it will only make changes /// to a blob if the current eTag matches, to ensure you don't overwrite someone else's changes.</param> /// <param name="md5">Provide the md5 and it will check and make sure it matches the blob's md5. /// If it doesn't match, it won't return a value.</param> /// <returns></returns> internal static System.Net.Http.Headers.AuthenticationHeaderValue GetAuthorizationHeader( string storageAccountName, string storageAccountKey, DateTime now, HttpRequestMessage httpRequestMessage, string ifMatch = "", string md5 = "") { // This is the raw representation of the message signature. HttpMethod method = httpRequestMessage.Method; String MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}", method.ToString(), (method == HttpMethod.Get || method == HttpMethod.Head) ? String.Empty : httpRequestMessage.Content.Headers.ContentLength.ToString(), ifMatch, GetCanonicalizedHeaders(httpRequestMessage), GetCanonicalizedResource(httpRequestMessage.RequestUri, storageAccountName), md5); // Now turn it into a byte array. byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature); // Create the HMACSHA256 version of the storage key. HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(storageAccountKey)); // Compute the hash of the SignatureBytes and convert it to a base64 string. string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)); // This is the actual header that will be added to the list of request headers. // You can stop the code here and look at the value of 'authHV' before it is returned. System.Net.Http.Headers.AuthenticationHeaderValue authHV = new System.Net.Http.Headers.AuthenticationHeaderValue("SharedKey", storageAccountName + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes))); return(authHV); }
public void AddAuthHeaders_WhenCalled_AddsDefaultRequestHeadersAuthorization() { var param = new System.Net.Http.Headers.AuthenticationHeaderValue("whatever"); _requestWrapper.AddAuthHeaders(param); Assert.AreEqual(_requestWrapper.AmSpaceHttpClient.DefaultRequestHeaders.Authorization, param); }
public AuthenticationHeaderValue(System.Net.Http.Headers.AuthenticationHeaderValue containedObject) { if ((containedObject == null)) { throw new System.ArgumentNullException("containedObject"); } this.containedObject = containedObject; }
static string GetTenantUriFromHeader(System.Net.Http.Headers.AuthenticationHeaderValue header) => header .Parameter .Replace("Bearer ", string.Empty) .Split(",") .Select(part => part.Split("=")) .ToDictionary(rg => rg[0], rg => rg[1])["authorization_uri"] .Trim('\'', '"');
private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader) { var rawCred = authHeader.Parameter; var encoding = Encoding.GetEncoding("iso-8859-1"); var cred = encoding.GetString(Convert.FromBase64String(rawCred)); var credArray = cred.Split(':'); return(credArray); }
public Airship(string applicationKey, string applicationSecretOrMasterSecret) { var textToEncode = $"{applicationKey}:{applicationSecretOrMasterSecret}"; var plainTextBytes = Encoding.ASCII.GetBytes(textToEncode); var base64String = Convert.ToBase64String(plainTextBytes); authorizationHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64String); }
private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext) { try { string JwtToken = null; //-------------------------------------------------------------------------------- //CHECK HEADER AUTHENTICATION System.Net.Http.Headers.AuthenticationHeaderValue header = actionContext.Request.Headers.Authorization; if (header == null) { //CHECK ACCESS_TOKEN in QUERY JwtToken = GetAccessTokenOnQuery(actionContext); } else { JwtToken = header.Parameter; } //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // CHECK EXISTENCE if (JwtToken == null) { _errorCode = "BEARER_TOKEN_NOT_FOUND"; return(false); } //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // CHECK JWT TOKEN var JwtVerifier = Gale.Security.Oauth.Jwt.Manager.ValidateToken(JwtToken); System.Web.HttpContext.Current.User = JwtVerifier; //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // IF RESTRICTED TO ROLEs, CHECK ALSO USERS (BASE METHOD CHECKER :P) if (!this.IsAuthorized(actionContext)) { _errorCode = "ACCESS_UNAUTHORIZED"; return(false); } //-------------------------------------------------------------------------------- return(true); } catch (System.IdentityModel.Tokens.SecurityTokenExpiredException) { _errorCode = "TOKEN_EXPIRED"; return(false); } catch (System.Exception) { _errorCode = "INVALID_TOKEN"; return(false); } }
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); } }
IExecuteController GetExecuteControllerInstance() { System.Net.Http.Headers.AuthenticationHeaderValue auth = null; if (Request != null) { if (Request.Headers != null) { auth = Request.Headers.Authorization; } } return(ExtensibilityUtility.GetExecuteControllerInstance(Url, User, auth)); }
public SonarQubeSvc( IHttpClientFactory httpClientFactory, IOptions <SonarQubeApiConfig> sonarQubeConfiguration) { _sonarQubeApiConfig = sonarQubeConfiguration.Value; var basicToken = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{sonarQubeConfiguration.Value.ApiKey}:")); var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", basicToken); _sonarQubeClient = httpClientFactory.CreateClient("SonarQube"); _sonarQubeClient.BaseAddress = sonarQubeConfiguration.Value.BaseUri; _sonarQubeClient.DefaultRequestHeaders.Authorization = authHeader; }
public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { var principal = context.ActionContext.RequestContext.Principal; if (AuthenticationUtility.IsAuthenticated(principal) || AuthenticationUtility.GetAuthorizationMode(context.ActionContext.ActionDescriptor) == AuthorizationMode.Anonymous) { return; } var challenge = new System.Net.Http.Headers.AuthenticationHeaderValue(HTTP_AUTHORIZATION_SCHEME); context.Result = new System.Web.Http.Results.UnauthorizedResult(new[] { challenge }, context.Request); }
public async Task RequestWithInvalidCredentials_ReturnsUnauthorized() { var request = new TestHttpRequest(WebServerUrl); var byteArray = Encoding.ASCII.GetBytes("root:password1233"); var authData = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", Convert.ToBase64String(byteArray)); request.Headers.Add("Authorization", authData.ToString()); using (var response = await SendAsync(request)) { Assert.AreEqual((int)HttpStatusCode.Unauthorized, response.StatusCode, "Status Code Unauthorized"); } }
private Task <HttpResponseMessage> MakeRequest(string?userName, string?password) { var request = new HttpRequestMessage(HttpMethod.Get, WebServerUrl); if (userName == null) { return(Client.SendAsync(request)); } var encodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{password}")); var authHeaderValue = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", encodedCredentials); request.Headers.Add("Authorization", authHeaderValue.ToString()); return(Client.SendAsync(request)); }
public override void OnAuthorization(HttpActionContext actionContext) { try { string actionName = actionContext.ActionDescriptor.ActionName; bool IsActionsWithOutValidation = actionName.Equals("Login") || actionName.Equals("SignUp"); if (IsActionsWithOutValidation) { return; } if (Thread.CurrentPrincipal.Identity.IsAuthenticated) { return; } System.Net.Http.Headers.AuthenticationHeaderValue authHeader = actionContext.Request.Headers.Authorization; if (authHeader != null) { if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(authHeader.Parameter)) { string TokenKey = authHeader.Parameter; int? UserID = Context.TokenManagerSelectByToken(Guid.Parse(TokenKey)).First(); if (UserID != 0) { GenericPrincipal principal = new GenericPrincipal(new GenericIdentity(UserID.ToString()), null); Thread.CurrentPrincipal = principal; return; } } } } } catch (Exception ex) { #if DEBUG // throw ex; #endif } HandleUnauthorized(actionContext); }
public async Task <ResourceGroupResponse> GetResourceGroupsAsync(string token) { var subscriptionId = _config.subscriptionId; var urlRgs = string.Format("https://management.azure.com/subscriptions/{0}/resourcegroups?api-version=2020-06-01", subscriptionId); var authorizationHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = authorizationHeader; var response = await client.GetStringAsync(urlRgs); var rgResponse = JsonSerializer.Deserialize <ResourceGroupResponse>(response); return(rgResponse); }
public async Task <APIResult <QLLuongDetailsViewModel> > Details(int IDLuong) { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration["BaseAddress"]); var session = _httpContextAccessor.HttpContext.Session.GetString("Token"); var httpContent = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", session); var response = await client.GetAsync($"/api/QLLuongs/{IDLuong}/details"); var body = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <APISuccessedResult <QLLuongDetailsViewModel> >(body)); } return(JsonConvert.DeserializeObject <APIErrorResult <QLLuongDetailsViewModel> >(body)); }
public async void Configure() { clientId = Environment.GetEnvironmentVariable("REDDITTOTUUSBOTTI_CLIENT_ID"); clientSecret = Environment.GetEnvironmentVariable("REDDITTOTUUSBOTTI_CLIENT_SECRET"); redditHttpClient = new HttpClient(); var redditCredentials = Encoding.ASCII.GetBytes(clientId + ":" + clientSecret); var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(redditCredentials)); redditHttpClient.DefaultRequestHeaders.Authorization = authHeader; redditWebAgent = new WebAgent(); if (isAccessTokenExpired()) { await RefreshAccessToken(); } redditClient = new Reddit(redditWebAgent, false); }
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; } } }
public virtual BasicAuthenticationIdentity FetchHeader(HttpActionContext context) { string authHeaderVal = null; System.Net.Http.Headers.AuthenticationHeaderValue authRequest = context.Request.Headers.Authorization; if (authRequest != null && !string.IsNullOrEmpty(authRequest.Scheme) && authRequest.Scheme == "Basic") // =>"do you have an auth header and a scheme called basic?" { authHeaderVal = authRequest.Parameter; } if (string.IsNullOrEmpty(authHeaderVal)) { return(null); } authHeaderVal = Encoding.Default.GetString(Convert.FromBase64String(authHeaderVal)); //converting authHeaderVal to a string. //pattern for header should be username:password string[] creds = authHeaderVal.Split(':'); //splits at ':' for "username:password" return(creds.Length < 2 ? null : new BasicAuthenticationIdentity(creds[0], creds[1])); }
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); } } }
public override async Task <DownloadUrlData> GetDownloadUri(Track track) { if (!Api.HasAuthenticated) { await Api.Authenticate(); } var auth = new System.Net.Http.Headers.AuthenticationHeaderValue(Api.CurrentOAuthAccount.TokenType, Api.CurrentOAuthAccount.Token); var url = (await Api.GetShareUrl(track.Id)).Replace("/redir?", "/download?"); var data = new DownloadUrlData() { Headers = new Dictionary <string, string> { { "Authorization", auth.ToString() }, }, Url = url, }; return(data); }
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 = "未授权访问" }); } }
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); }