public StoreRestClients(AuthenticationBase authSession, AdlClient.Models.StoreAccountRef account) { this.Account = account; this.FileSystemClient = new DataLakeStoreFileSystemManagementClient(authSession.AdlCreds); this.AccountClient = new DataLakeStoreAccountManagementClient(authSession.ArmCreds); this.AccountClient.SubscriptionId = account.SubscriptionId; }
public async Task <T> PatchAsync <T, M>(AuthenticationBase authentication, string address, M model) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); var request = new HttpRequestMessage(new HttpMethod("PATCH"), address); var jsonModel = JsonConvert.SerializeObject(model); request.Content = new StringContent(jsonModel, Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await client.SendAsync(request)) { // will throw an exception if not successful response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var resultObject = JsonConvert.DeserializeObject <T>(responseBody); return(resultObject); } } }
internal GraphCommands(AuthenticationBase auth) { this.Authentication = auth; this.GraphClient = new Microsoft.Azure.Graph.RBAC.GraphRbacManagementClient(auth.GraphCreds); this.GraphClient.TenantID = auth.Tenant; }
public async Task <T> GetAsync <T>(AuthenticationBase authentication, string address) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); using (HttpResponseMessage response = client.GetAsync(address).Result) { // will throw an exception if not successful response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new Exception(responseBody); } try { return(JsonConvert.DeserializeObject <T>(responseBody)); } catch (Exception) { throw new Exception("Unable to convert results: " + responseBody); } } } }
public HttpWebResponse RequestFile(AuthenticationBase authentication, string address, string httpMethod = "GET") { HttpWebResponse response = null; try { var request = (HttpWebRequest)WebRequest.Create(address); request.UserAgent = "VSTS-Get"; request.Headers.Set(HttpRequestHeader.Authorization, GetAuthenticationHeaderValue(authentication).ToString()); request.ContentType = "application/json"; request.Method = httpMethod; response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; } } catch (Exception) { response?.Close(); } return(response); }
public StoreClient(AuthenticationBase auth, AdlClient.Models.StoreAccountRef account) : base(auth) { this.RestClients = new AdlClient.Rest.StoreRestClients(auth, account); this.FileSystem = new AdlClient.Commands.FileSystemCommands(account, this.RestClients); this.Account = new AdlClient.Commands.StoreAccountCommands(account, this.RestClients); }
public async Task <T> PostAsync <T>(AuthenticationBase authentication, string address, T model) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); //var content = new ObjectContent<T>(model, new JsonMediaTypeFormatter()); var request = new HttpRequestMessage(new HttpMethod("PATCH"), address); string jsonModel = Newtonsoft.Json.JsonConvert.SerializeObject(model); var content = new StringContent(jsonModel, Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await client.PostAsync(address, content)) { // will throw an exception if not successful //response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); if (typeof(T) == typeof(string)) { return((T)(object)responseBody); } var resultObject = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseBody); return(resultObject); } } }
/// <summary> /// 登录 /// POST /api/login /// </summary> /// <param name="username">用户名</param> /// <param name="pwd">密码</param> public static async Task <AuthenticationBase> Login(string username, string pwd = null) { try { Dictionary <string, string> dic_content = new Dictionary <string, string>(); dic_content.Add("username", username); if (!string.IsNullOrEmpty(pwd)) { dic_content.Add("password", pwd); } FormUrlEncodedContent content = new FormUrlEncodedContent(dic_content); var response = await client.PostAsync(host + "/api/login", content); var stringresponse = await response.Content.ReadAsStringAsync(); var loginobj = JsonConvert.DeserializeObject <loginresponse>(stringresponse); var auth = new AuthenticationBase { IsAuthSuccess = loginobj.authenticated, Message = (loginobj.errors ?? (object)"").ToString() }; return(auth); } catch (Exception ex) { var auth = new AuthenticationBase { IsAuthSuccess = false, Message = ex.Message }; return(auth); } }
public HomeController(AuthenticationBase authService, IHotelAndLocation hotelService, IAnteeoCaching anteeoCaching, IConfig configService) { _authService = authService; _hotelService = hotelService; _cachingService = anteeoCaching; _configService = configService; }
public void SetHeaders(HeaderList AHeaders) { string S = ""; if (_Authentication != null) { S = _Authentication.Authentication(); if (S.Length > 0) { AHeaders.Values("Proxy-Authentication", S); } } else { if (_BasicByDefault) { _Authentication = new BasicAuthentication(); _Authentication.UserName = _UserName; _Authentication.Password = _Password; S = _Authentication.Authentication(); if (S.Length > 0) { AHeaders.Values("Proxy-Authentication", S); } } } }
private string GetBasicAuthenticationHeaderValue(AuthenticationBase authentication) { var headerValue = string.Empty; if (authentication is BasicAuthentication basicAuthentication) { headerValue = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{basicAuthentication.UserName}:{basicAuthentication.Password}"))}"; } return(headerValue); }
public async Task DeleteAsync(AuthenticationBase authentication, string address) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); using (var response = await client.DeleteAsync(address)) { // will throw an exception if not successful response.EnsureSuccessStatusCode(); } } }
private static IDataServerSecurity CreateDataServerSecurity(AuthenticationBase authentication) { CustomCreateDataServerSecurityEventArgs args = new CustomCreateDataServerSecurityEventArgs { UserType = UserType ?? typeof(SecuritySystemUser), RoleType = RoleType ?? typeof(SecuritySystemRole), Authentication = authentication }; CustomCreateDataServerSecurity?.Invoke(null, args); return(args.Security ?? new SecurityStrategyComplex(args.UserType, args.RoleType, authentication)); }
public async Task PutAsync(AuthenticationBase authentication, string address, StringContent content) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); using (var response = await client.PutAsync(address, content)) { // will throw an exception if not successful response.EnsureSuccessStatusCode(); } } }
private AuthenticationHeaderValue GetAuthenticationHeaderValue(AuthenticationBase authentication) { if (authentication is BasicAuthentication basicAuthentication) { return(new AuthenticationHeaderValue("Basic", Convert.ToBase64String( Encoding.UTF8.GetBytes($"{basicAuthentication.UserName}:{basicAuthentication.Password}")))); } if (authentication is OAuthAuthorization oauthAuthorization) { return(new AuthenticationHeaderValue("Bearer", oauthAuthorization.accessToken)); } throw new InvalidCastException("Authentication type is unknown."); }
public async Task <T> PostAsync <T>(AuthenticationBase authentication, string address, T model) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(address); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); using (var response = client.PostAsJsonAsync <T>(client.BaseAddress, model)) { var responseBody = await response.Result.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(responseBody)); } } }
public async Task <T> PutAsync <T>(AuthenticationBase authentication, string address, StringContent content) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = GetAuthenticationHeaderValue(authentication); using (HttpResponseMessage response = await client.PutAsync(address, content)) { // will throw an exception if not successful response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); var resultObject = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseBody); return(resultObject); } } }
private AuthenticationHeaderValue GetAuthenticationHeaderValue(AuthenticationBase authentication) { var basicAuthentication = authentication as BasicAuthentication; if (basicAuthentication != null) { return(new AuthenticationHeaderValue("Basic", Convert.ToBase64String( UTF8Encoding.UTF8.GetBytes( string.Format("{0}:{1}", basicAuthentication.UserName, basicAuthentication.Password))))); } var oauthAuthorization = authentication as OAuthAuthorization; if (oauthAuthorization != null) { return(new AuthenticationHeaderValue("Bearer", oauthAuthorization.accessToken)); } throw new InvalidCastException("Authentication type is unknown."); }
protected override void DoExecute(object sender, ContextRunEventArgs <int, ReplyRFC, ContextRFC> eventArgs) { HttpRequestInfo LRequestInfo; HttpResponseInfo LResponseInfo; bool ContinueProcessing = true; string S = ""; string sCmd = ""; string sVersion = ""; string sRequestURI = ""; URI LURI; bool LCloseConnection = !KeepAlive; string LRawHttpCommand = ""; try { try { do { LRawHttpCommand = eventArgs.Context.TcpConnection.Socket.ReadLn(); string[] commandParts = LRawHttpCommand.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); switch (commandParts.Length) { case 2: sCmd = commandParts[0].ToUpper(); sRequestURI = "/"; sVersion = commandParts[1]; break; case 3: sCmd = commandParts[0].ToUpper(); sRequestURI = commandParts[1]; sVersion = commandParts[2]; break; default: throw new HTTPErrorParsingCommandException(ResourceStrings.ErrorParsingCommand); } // TODO: Check for 1.0 only at this point using (LRequestInfo = new HttpRequestInfo(LRawHttpCommand, eventArgs.Context.TcpConnection.Socket.EndPoint, sCmd, eventArgs.Context)) { LRequestInfo.RawHttpCommand = LRawHttpCommand; LRequestInfo.RawHeaders.Clear(); eventArgs.Context.TcpConnection.Socket.MaxCapturedLines = MaximumHeaderLineCount; eventArgs.Context.TcpConnection.Socket.Capture(LRequestInfo.RawHeaders, String.Empty); LRequestInfo.ProcessHeaders(); // TODO: This is the area that needs fixed. Ive hacked it for now // Get data can exists with POSTs, but can POST data exist with GETs? // If only the first, the solution is easy. If both - need more // investigation. LRequestInfo.PostStream = null; Stream TempStream = LRequestInfo.__PostStream; CreatePostStream(eventArgs.Context, out TempStream); LRequestInfo.__PostStream = TempStream; if (LRequestInfo.PostStream == null) { LRequestInfo.__PostStream = new MemoryStream(); } if (LRequestInfo.ContentLength > 0) { eventArgs.Context.TcpConnection.Socket.ReadStream(LRequestInfo.PostStream, LRequestInfo.ContentLength); } else { if (sCmd == "POST") { if (!LRequestInfo.HasContentLength) { eventArgs.Context.TcpConnection.Socket.ReadStream(LRequestInfo.PostStream, -1, true); } } } LRequestInfo.__Command = sCmd; LRequestInfo.PostStream.Position = 0; LRequestInfo.__FormParams = new StreamReader(LRequestInfo.PostStream).ReadToEnd(); LRequestInfo.__UnparsedParams = LRequestInfo.FormParams; LRequestInfo.__QueryParams = sRequestURI.IndexOf("?") >= 0 ? sRequestURI.Substring(sRequestURI.IndexOf("?") + 1) : string.Empty; // LRequestInfo.__RemoteIP = ((new IPEndPoint(. eventArgs.Context.TcpConnection.Socket.EndPoint).Address; // LRequestInfo.__RemotePort = ((IPEndPoint)eventArgs.Context.TcpConnection.Socket.EndPoint).Port; if (LRequestInfo.QueryParams.Length > 0) { if (LRequestInfo.UnparsedParams.Length == 0) { LRequestInfo.__UnparsedParams = LRequestInfo.QueryParams; } else { LRequestInfo.__UnparsedParams += "&" + LRequestInfo.QueryParams; } } if (ParseParams) { if (LRequestInfo.ContentType.ToLower() == "application/x-www-form-urlencoded") { LRequestInfo.DecodeAndSetParams(LRequestInfo.UnparsedParams); } else { LRequestInfo.DecodeAndSetParams(LRequestInfo.QueryParams); } } ReadCookiesFromRequestHeader(LRequestInfo); LRequestInfo.__Version = sVersion; LRequestInfo.RequestURI = sRequestURI; if (sRequestURI == "*") { LRequestInfo.__Document = "*"; } else { LURI = new URI(sRequestURI); LRequestInfo.__Document = URI.URLDecode(LURI.Document); if (LURI.Host.Length > 0 && LRequestInfo.Host.Length == 0) { LRequestInfo.__Host = LURI.Host; } } S = LRequestInfo.RawHeaders.Values("Authorization"); LRequestInfo.__AuthExists = S.Length > 0; if (LRequestInfo.AuthExists) { string AuthMethod = Global.Fetch(ref S, " "); if (AuthenticationRegistry.FindAuthenticationMethod(AuthMethod) != null) { using (AuthenticationBase ab = AuthenticationRegistry.GetAuthenticationMethodHandler(AuthMethod)) { ab.DecodeAuthParams(S); LRequestInfo.__AuthUserName = ab.UserName; LRequestInfo.__AuthPassword = ab.Password; } } else { throw new HTTPUnsupportedAuthorisationSchemeException(ResourceStrings.UnsupportedAuthorizationScheme); } } using (LResponseInfo = new HttpResponseInfo(eventArgs.Context.TcpConnection)) { try { LResponseInfo.CloseConnection = !(_KeepAlive && LRequestInfo.Connection.Equals("Keep-alive", StringComparison.InvariantCultureIgnoreCase)); GetSessionFromCookie(eventArgs.Context, LRequestInfo, LResponseInfo, out ContinueProcessing); if (ServerSoftware.Trim().Length > 0) { LResponseInfo.ServerSoftware = ServerSoftware; } try { if (ContinueProcessing) { HandleCommand(eventArgs.Context, LRequestInfo, LResponseInfo); } } catch (SocketException) { throw; } catch (Exception E) { LResponseInfo.ResponseNo = 500; LResponseInfo.ContentText = E.Message; LResponseInfo.ContentType = "text/plain"; } if (!LResponseInfo.HeaderHasBeenWritten) { LResponseInfo.WriteHeader(); } if (LResponseInfo.ContentText.Length > 0 || LResponseInfo.ContentStream != null) { LResponseInfo.WriteContent(); } } finally { LCloseConnection = LResponseInfo.CloseConnection; } } } }while (!LCloseConnection); } catch (SocketException E) { if (E.ErrorCode != 10054) // WSAECONNRESET { throw; } } catch (ClosedSocketException) { eventArgs.Context.TcpConnection.Disconnect(); } catch (Exception) { throw; } } finally { eventArgs.Context.TcpConnection.Disconnect(false); } eventArgs.ReturnValue = false; }
public CustomSecurityStrategyComplex(Type userType, Type roleType, AuthenticationBase autentificationBase) : base(userType, roleType, autentificationBase) { }
public UbConnection(Uri baseUri, AuthenticationBase auth) { _transport = new UbTransport(baseUri); BaseUri = baseUri; _auth = auth; }
internal AnalyticsRmCommands(InteractiveAuthentication auth) { this.Authentication = auth; }
protected override void DoSetHeaders() { base.DoSetHeaders(); if (_ProxyConnection.Length > 0) { _RawHeaders.Values("Proxy-Connection", _ProxyConnection); } if (_Host.Length > 0) { _RawHeaders.Values("Host", _Host); } if (_Accept.Length > 0) { _RawHeaders.Values("Accept", _Accept); } if (_AcceptCharSet.Length > 0) { _RawHeaders.Values("Accept-Charset", _AcceptCharSet); } if (_AcceptEncoding.Length > 0) { _RawHeaders.Values("Accept-Language", _AcceptLanguage); } if (_From.Length > 0) { _RawHeaders.Values("From", _From); } if (_Referer.Length > 0) { _RawHeaders.Values("Referer", _Referer); } if (_UserAgent.Length > 0) { _RawHeaders.Values("User-Agent", _UserAgent); } if (_LastModified.Ticks > 0) { _RawHeaders.Values("If-Modified-Since", Http.DateTimeGmtToHttpStr(_LastModified)); } if (_ContentRangeStart != 0 || _ContentRangeEnd != 0) { if (_ContentRangeEnd != 0) { _RawHeaders.Values("Range", "bytes=" + _ContentRangeStart.ToString() + "-" + _ContentRangeEnd.ToString()); } else { _RawHeaders.Values("Range", "bytes=" + _ContentRangeStart.ToString() + "-"); } } if (_Authentication != null) { string S = _Authentication.Authentication(); if (S.Length > 0) { _RawHeaders.Values("Authorization", S); } } else { if (_BasicByDefault) { _Authentication = new BasicAuthentication(); _Authentication.UserName = _UserName; _Authentication.Password = _Password; string S = _Authentication.Authentication(); if (S.Length > 0) { _RawHeaders.Values("Authorization", S); } } } }
/// <summary> /// Updates individual properties of an existing access policy resource. /// </summary> /// <remarks> /// Updates individual properties of an existing access policy resource with /// the given name. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='accountName'> /// The Azure Video Analyzer account name. /// </param> /// <param name='accessPolicyName'> /// The Access Policy name. /// </param> /// <param name='role'> /// Defines the access level granted by this policy. Possible values include: /// 'Reader' /// </param> /// <param name='authentication'> /// Authentication method to be used when validating client API access. /// </param> public static AccessPolicyEntity Update(this IAccessPoliciesOperations operations, string resourceGroupName, string accountName, string accessPolicyName, AccessPolicyRole?role = default(AccessPolicyRole?), AuthenticationBase authentication = default(AuthenticationBase)) { return(operations.UpdateAsync(resourceGroupName, accountName, accessPolicyName, role, authentication).GetAwaiter().GetResult()); }
public void AuthenticationBase_QuoteCmdArg(string input, string expected) { string actual = AuthenticationBase.QuoteCmdArg(input); Assert.Equal(expected, actual); }
public TralusSecurityStrategy(AuthenticationBase authentication) : base(typeof(User), typeof(Role), authentication) { }
/// <summary> /// Updates individual properties of an existing access policy resource. /// </summary> /// <remarks> /// Updates individual properties of an existing access policy resource with /// the given name. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='accountName'> /// The Azure Video Analyzer account name. /// </param> /// <param name='accessPolicyName'> /// The Access Policy name. /// </param> /// <param name='role'> /// Defines the access level granted by this policy. Possible values include: /// 'Reader' /// </param> /// <param name='authentication'> /// Authentication method to be used when validating client API access. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <AccessPolicyEntity> UpdateAsync(this IAccessPoliciesOperations operations, string resourceGroupName, string accountName, string accessPolicyName, AccessPolicyRole?role = default(AccessPolicyRole?), AuthenticationBase authentication = default(AuthenticationBase), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, accessPolicyName, role, authentication, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
internal ClientBase(AuthenticationBase auth) { this.Authentication = auth; }