public LoginData(string server, string login, string password, AuthMethod auth) { Server = server; Login = login; Password = password; AuthMethod = auth; }
public async Task <IActionResult> PutAuthMethod(int id, AuthMethod authMethod) { if (id != authMethod.AuthMethodId) { return(BadRequest()); } _context.Entry(authMethod).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AuthMethodExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task IssuingTokenGeneratesTokenAndIdentityWithScopes(AuthMethod authMethod, params string[] scopes) { CommunicationIdentityClient client = authMethod switch { AuthMethod.ConnectionString => CreateClientWithConnectionString(), AuthMethod.KeyCredential => CreateClientWithAzureKeyCredential(), AuthMethod.TokenCredential => CreateClientWithTokenCredential(), _ => throw new ArgumentOutOfRangeException(nameof(authMethod)), }; Response <CommunicationUserIdentifier> userResponse = await client.CreateUserAsync(); Response <CommunicationUserToken> tokenResponse = await client.IssueTokenAsync(userResponse.Value, scopes : scopes.Select(x => new CommunicationTokenScope(x))); Assert.IsNotNull(tokenResponse.Value); Assert.IsFalse(string.IsNullOrWhiteSpace(tokenResponse.Value.Token)); ValidateScopesIfNotSanitized(); void ValidateScopesIfNotSanitized() { if (Mode != RecordedTestMode.Playback) { JwtTokenParser.JwtPayload payload = JwtTokenParser.DecodeJwtPayload(tokenResponse.Value.Token); CollectionAssert.AreEquivalent(scopes, payload.Scopes); } } }
protected override void CheckRequest(GStatsSession session, Dictionary <string, string> recv) { base.CheckRequest(session, recv); if (recv.ContainsKey("pid") && recv.ContainsKey("resp")) { //we parse profileid here if (!uint.TryParse(recv["pid"], out _profileid)) { _errorCode = GstatsErrorCode.Parse; } _authMethod = AuthMethod.ProfileIDAuth; } else if (recv.ContainsKey("authtoken") && recv.ContainsKey("response")) { _authMethod = AuthMethod.PartnerIDAuth; } else if (recv.ContainsKey("keyhash") && recv.ContainsKey("nick")) { _authMethod = AuthMethod.CDkeyAuth; } else { _errorCode = GstatsErrorCode.Parse; } }
public AKVConfigurationProvider(AuthMethod useLocalCert, string secret, string keyvaultbase, string appclientid) { _useLocalCert = useLocalCert; _secret = secret; _keyvaultbase = keyvaultbase; _appclientid = appclientid; }
public async Task MountDefaultAppRoleMount_Success() { AppRoleAuthEngine defaultBE = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole); AuthMethod defaultAM = new AuthMethod(defaultBE.MountPoint, EnumAuthMethods.AppRole); try { Assert.True(await _vaultSystemBackend.AuthEnable(defaultAM)); } catch (VaultException e) { if (e.SpecificErrorCode == EnumVaultExceptionCodes.BackendMountAlreadyExists) { // Disable and re-enable to confirm we can do this. Assert.True(await _vaultSystemBackend.AuthDisable(defaultAM)); Assert.True(await _vaultSystemBackend.AuthEnable(defaultAM)); } else { Assert.Fail("Unexpected Vault Error - " + e.Message); } } catch (Exception e) { Assert.Fail("Unexpected error from Vault: " + e.Message); } string name = _uniqueKeys.GetKey("RoleDef"); AppRole ar = new AppRole(name); Assert.True(await _appRoleAuthEngine.SaveRole(ar)); }
public async Task AppRoleLoginConnector_Test() { // PRE-Test VaultSystemBackend vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault); string approleMountName = _UK.GetKey("AppAuth"); // Create an AppRole authentication connection. AppRoleAuthEngine appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "AppRole", approleMountName); // Create an Authentication method of App Role. - This only needs to be done when the Auth method is created. AuthMethod am = new AuthMethod(approleMountName, EnumAuthMethods.AppRole); bool rc = await vaultSystemBackend.AuthEnable(am); string rName = _UK.GetKey("Role"); AppRole roleA = new AppRole(rName); Assert.True(await appRoleAuthEngine.SaveRole(roleA)); string roleID = await appRoleAuthEngine.ReadRoleID(roleA.Name); // Now create the a secret AppRoleSecret secret_A = await appRoleAuthEngine.GenerateSecretID(roleA.Name); // ACTUAL TEST // Create Login Connector AppRoleLoginConnector loginConnector = new AppRoleLoginConnector(_vault, approleMountName, "Test AppRole", roleID, secret_A.ID); bool result = await loginConnector.Connect(true); Assert.IsTrue(result, "A10: Login Failed"); }
public async Task <ActionResult <AuthMethod> > PostAuthMethod(AuthMethod authMethod) { _context.AuthMethod.Add(authMethod); await _context.SaveChangesAsync(); return(CreatedAtAction("GetAuthMethod", new { id = authMethod.AuthMethodId }, authMethod)); }
private UserInfo GetUser(out AuthMethod method) { if (LoginWithThirdParty.TryGetUserByHash(HashId, out var userId)) { if (!(CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Oauth)) { throw new Exception(Resource.ErrorNotAllowedOption); } method = AuthMethod.ThirdParty; return(CoreContext.UserManager.GetUsers(userId)); } if (EnableLdap && !string.IsNullOrEmpty(Request["ldapPassword"])) { var localization = new LdapLocalization(Resource.ResourceManager); var ldapUserManager = new LdapUserManager(localization); UserInfo userInfo; //todo: think about password if (!ldapUserManager.TryGetAndSyncLdapUserInfo(Login, PasswordHash, out userInfo)) { userInfo = Constants.LostUser; } method = AuthMethod.Ldap; return(userInfo); } method = AuthMethod.Login; return(CoreContext.UserManager.GetUsersByPasswordHash(TenantProvider.CurrentTenantID, Login, PasswordHash)); }
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { var request = new RestRequest(BuildUri(), _method); request.RequestFormat = DataFormat.Json; SetAuthentication(request, authMethod, sessionId); if (Data != null) { AddParameter("data", Data); // will be handled by upcoming loop } foreach (var param in _parameters) { if (param.Value is string) { request.AddParameter(param.Key, param.Value); } else if (param.Value is int) { request.AddParameter(param.Key, param.Value.ToString()); } else { var serialized = request.JsonSerializer.Serialize(param.Value); request.AddParameter(param.Key, serialized); } } if (Body != null) { request.AddBody(Body); } return(request); }
public bool UpdateAuth(string value) { if (string.IsNullOrEmpty(value)) { Auth = null; return(true); } if (value.StartsWith("Bearer ")) { Auth = new AuthToken(); } else if (value.StartsWith("Basic ")) { Auth = new AuthBasic(); } else { var lower = value.ToLowerInvariant(); if (lower.StartsWith("api-key") || lower.StartsWith("apikey")) { Auth = new AuthApiKey(); } else { Auth = new AuthCustom(); } } return(Auth.FromValue(value)); }
public async Task Auth_EnableDisableValidated() { string name = _uniqueKeys.GetKey("TST"); AuthMethod am = new AuthMethod(name, EnumAuthMethods.AppRole); string path = am.Path; Debug.WriteLine("EnDisValid: Enabling first"); Assert.True(await _vaultSystemBackend.AuthEnable(am)); // Now get listing of methods and search for our test one. Debug.WriteLine("EnDisValid: Getting List."); Dictionary <string, AuthMethod> authMethods = await _vaultSystemBackend.AuthListAll(); Assert.NotNull(authMethods); Assert.That(authMethods, Contains.Key(path)); // Now disable and verify it is not in list. Debug.WriteLine("EnDisValid: Disabling..."); Assert.True(await _vaultSystemBackend.AuthDisable(am)); Debug.WriteLine("EnDisValid: Get new list LatestMethods..."); Dictionary <string, AuthMethod> latestMethods = await _vaultSystemBackend.AuthListAll(); Debug.WriteLine("EnDisValid: Final Asserts"); Assert.NotNull(latestMethods); Assert.That(latestMethods, !Contains.Key(path)); }
public LoginData(string server, string login, string password, AuthMethod auth) { Server = server; Login = login; Password = password; AuthMethod = auth; }
private async Task Validate(HttpContext httpContext, DataContext dataContext) { httpContext.Response.Clear(); httpContext.Response.StatusCode = 400; var accessToken = httpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); if (accessToken == null) { await httpContext.Response.WriteAsync("Missing access token!"); return; } var validatedToken = AuthMethod.ValidateJSONWebToken(accessToken, _config["Jwt:AccessTokenSecret"], _config["Jwt:Issuer"], _config["Jwt:Audience"]); if (validatedToken == null) { await httpContext.Response.WriteAsync("Incorrect access token!"); return; } httpContext.Items["user"] = await dataContext.Users.FindAsync(validatedToken); }
void StartAuthentication() { if ((AuthMethodsSupported & AuthMethod.MD5) == AuthMethod.MD5) { AuthMethodUsed = AuthMethod.MD5; XMPPClient.SendRawXML(MD5Auth); } else if (((AuthMethodsSupported & AuthMethod.Plain) == AuthMethod.Plain) && (XMPPClient.UseTLS == true)) { AuthMethodUsed = AuthMethod.Plain; byte[] bUserName = System.Text.UTF8Encoding.UTF8.GetBytes(XMPPClient.UserName); byte[] bPassword = System.Text.UTF8Encoding.UTF8.GetBytes(XMPPClient.Password); byte[] bText = new byte[2 + bUserName.Length + bPassword.Length]; bText[0] = 0; Array.Copy(bUserName, 0, bText, 1, bUserName.Length); bText[bUserName.Length + 1] = 0; Array.Copy(bPassword, 0, bText, 1 + bUserName.Length + 1, bPassword.Length); string strBase64Text = Convert.ToBase64String(bText); string ResponseMessage = PlainAuth.Replace("##RESPONSE##", strBase64Text); XMPPClient.SendRawXML(ResponseMessage); } // Needs some type of google token retrieved from http or something //else if (((AuthMethodsSupported & AuthMethod.googletoken) == AuthMethod.googletoken) && (XMPPClient.UseTLS == true)) //{ // AuthMethodUsed = AuthMethod.googletoken; // string strText = string.Format("\0{0}@{1}\0{2}", XMPPClient.UserName, XMPPClient.Domain, XMPPClient.Password); // byte[] bText = System.Text.UTF8Encoding.UTF8.GetBytes(strText); // string strBase64Text = Convert.ToBase64String(bText); // string ResponseMessage = PlainAuth.Replace("##RESPONSE##", strBase64Text); // XMPPClient.SendRawXML(ResponseMessage); //} }
private void Negotiate_ReadWhole_End(IAsyncResult ar) { Negotiation_SO asyncState = (Negotiation_SO)ar.AsyncState; try { asyncState.UpdateContext(); this.EndReadWhole(ar); AuthMethod method = this.ExtractAuthMethod(asyncState.Reply); if (((AuthMethod.NoAcceptable == method) && !asyncState.UseCredentials) && (base._proxyUser != null)) { asyncState.UseCredentials = true; byte[] buffer = this.PrepareNegotiationCmd(asyncState.UseCredentials); base.NStream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(this.Negotiate_Write_End), asyncState); } else { this.BeginDoAuthentication(method, new AsyncCallback(this.Negotiate_DoAuth_End), asyncState); } } catch (Exception exception) { asyncState.Exception = exception; asyncState.SetCompleted(); } }
public async Task GettingTurnCredentialsWithRequestedRouteType(AuthMethod authMethod, RouteType routeType) { CommunicationRelayClient client = authMethod switch { AuthMethod.ConnectionString => CreateClientWithConnectionString(), AuthMethod.KeyCredential => CreateClientWithAzureKeyCredential(), AuthMethod.TokenCredential => CreateClientWithTokenCredential(), _ => throw new ArgumentOutOfRangeException(nameof(authMethod)), }; CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient(); Response <CommunicationUserIdentifier> userResponse = await communicationIdentityClient.CreateUserAsync(); Response <CommunicationRelayConfiguration> turnCredentialsResponse = await client.GetRelayConfigurationAsync(userResponse.Value, routeType); Assert.IsNotNull(turnCredentialsResponse.Value); Assert.IsNotNull(turnCredentialsResponse.Value.ExpiresOn); Assert.IsNotNull(turnCredentialsResponse.Value.IceServers); foreach (CommunicationIceServer serverCredential in turnCredentialsResponse.Value.IceServers) { foreach (string url in serverCredential.Urls) { Assert.IsFalse(string.IsNullOrWhiteSpace(url)); } Assert.IsFalse(string.IsNullOrWhiteSpace(serverCredential.Username)); Assert.IsFalse(string.IsNullOrWhiteSpace(serverCredential.Credential)); Assert.AreEqual(routeType, serverCredential.RouteType); } }
public async Task Setup() { // Build Connection to Vault. _vault = await VaultServerRef.ConnectVault("AppRoleVault"); //_vault = new VaultAgentAPI ("AppRoleVault", VaultServerRef.ipAddress, VaultServerRef.ipPort, VaultServerRef.rootToken, true); _vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault); _ldapMountName = _uniqueKeys.GetKey("LDAP"); // Define the engine. _ldapAuthEngine = (LdapAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_LDAP, "ldap_test", _ldapMountName); // Now create the Mount point. AuthMethod authMethod = new AuthMethod(_ldapMountName, EnumAuthMethods.LDAP); authMethod.Description = "Ldap Test"; Assert.True(await _vaultSystemBackend.AuthEnable(authMethod), "A10: Expected the LDAP Backend to have been enabled."); // Now build the LDAP Backend. _origConfig = _ldapAuthEngine.GetLDAPConfigFromFile(@"C:\a_Dev\Configs\LDAP_Test.json"); SetLDAPConfig(_ldapMountName, _origConfig); // Save the Config. We do this here so the SetLDAPConfig can be used for multiple engines. Assert.True(await _ldapAuthEngine.ConfigureLDAPBackend(_origConfig), "A100: Expected the LDAP Configuration method to return True"); // Initialize the LDAP Login Connector. _ldapLoginConnector = new LDAPLoginConnector(_vault, _ldapAuthEngine.MountPoint, "Test LDAP Backend"); // Load the Test Data Object LoadTestData(); }
private UserInfo GetUser(out AuthMethod method) { if (EnableLdap) { var localization = new LdapLocalization(Resource.ResourceManager); var ldapUserManager = new LdapUserManager(localization); UserInfo userInfo; if (ldapUserManager.TryGetAndSyncLdapUserInfo(Login, Password, out userInfo)) { method = AuthMethod.Ldap; return(userInfo); } } Guid userId; if (LoginWithThirdParty.TryGetUserByHash(HashId, out userId)) { method = AuthMethod.ThirdParty; return(CoreContext.UserManager.GetUsers(userId)); } method = AuthMethod.Login; return(CoreContext.UserManager.GetUsers(TenantProvider.CurrentTenantID, Login, Hasher.Base64Hash(Password, HashAlg.SHA256))); }
public void AuthMethod_ConstructViaEnum_Success(EnumAuthMethods i, string val) { string sPath = "GHI" + i.ToString(); AuthMethod am = new AuthMethod(sPath, i); Assert.AreEqual(am.TypeAsString, val); }
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { var request = new RestRequest(ResourceUris.Logout, Method.POST); SetAuthentication(request, authMethod, sessionId); return(request); }
/// <summary> /// 调用接口返回数据 /// </summary> /// <param name="pageIndex"></param> /// <param name="accId"></param> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public string GetWeixinFeedBack(int pageIndex, string accId, string start, string end) { ProxyRequestModel.ProxyRequest request = new ProxyRequestModel.ProxyRequest(); ProxyRequestModel.UserMessage usrMsg = new ProxyRequestModel.UserMessage(); Dictionary <string, string> dic = new Dictionary <string, string>() { { "listData", "" }, { "rowCount", "" }, { "maxPage", "" } }; usrMsg.pageIndex = pageIndex; usrMsg.pageSize = 15; if (!string.IsNullOrEmpty(start)) { usrMsg.startTime = Convert.ToDateTime(start); } if (!string.IsNullOrEmpty(end)) { usrMsg.endTime = Convert.ToDateTime(end); } if (int.Parse(accId) != 0) { usrMsg.accId = Convert.ToInt32(accId); request.RequestName = "getMessageByAccId"; } else { usrMsg.accId = 0; request.RequestName = "getMessage"; } request.RequestJson = CommonLib.Helper.JsonSerializeObject(usrMsg); ProxyRequestModel.WeixinResponseModel response = new ProxyRequestModel.WeixinResponseModel(); response = AuthMethod.SendRequest(request); if (response.Status) { OpenResponseModel.ResponseMessage responseModel = CommonLib.Helper.JsonDeserializeObject <OpenResponseModel.ResponseMessage>(response.ObjectStr); foreach (OpenResponseModel.T_UserMessageModel item in responseModel.userMessage) { item.CompanyName = T_AccountBLL.GetSingleCompanyName(item.accId); } dic["listData"] = CommonLib.Helper.JsonSerializeObject(responseModel.userMessage, "yyyy-MM-dd HH:mm:ss"); dic["rowCount"] = responseModel.pageInfo.totalCount.ToString(); dic["maxPage"] = responseModel.pageInfo.pageCount.ToString(); return(CommonLib.Helper.JsonSerializeObject(dic, "yyyy-MM-dd HH:mm:ss")); } else { return("API接口调用出错!"); } }
public async Task Auth_Disable_Works() { string key = _uniqueKeys.GetKey("TST"); AuthMethod am = new AuthMethod(key, EnumAuthMethods.AppRole); Assert.True(await _vaultSystemBackend.AuthEnable(am)); Assert.True(await _vaultSystemBackend.AuthDisable(am)); }
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { var request = new RestRequest(BuildUrl(), _method); SetAuthentication(request, authMethod, sessionId); request.AddParameter("ids", _userId); request.AddParameter("globalgroup", _globalGroup); return request; }
// Make sure that specifying a name value will build the appropriate path value. public void AuthMethod_Constructor_SetsNameAndPathCorrectly_WhenProvidedName() { string name = "test2"; string path = name + "/"; AuthMethod am = new AuthMethod(name, EnumAuthMethods.Kubernetes); Assert.AreEqual(path, am.Path); Assert.AreEqual(name, am.Name); }
/// <summary> /// Enables the provided Authentication backend. /// </summary> /// <param name="am">The AuthMethod object that represents the authentication engine to enable.</param> /// <returns>True if authentication engine was successfully enabled. False otherwise. /// Throws exception: VaultException with SpecificErrorCode set to BackendMountAlreadyExists if a mount already exists at that location. /// </returns> public async Task <bool> AuthEnable(AuthMethod am) { string path = MountPointPath + "auth/" + am.Name; Dictionary <string, string> contentParams = new Dictionary <string, string>(); contentParams.Add("path", am.Path); contentParams.Add("description", am.Description); contentParams.Add("type", am.TypeAsString); string contentJSON = JsonConvert.SerializeObject(contentParams, Formatting.None); StringBuilder jsonConfig; string json = ""; if (am.Config != null) { jsonConfig = new StringBuilder(JsonConvert.SerializeObject(am.Config)); jsonConfig.Insert(0, "\"config\":"); // Combine the 2 JSON's, by stripping trailing closing brace from the content param JSON string. StringBuilder jsonParams = new StringBuilder(contentJSON, (contentJSON.Length + jsonConfig.Length + 20)); jsonParams.Remove(jsonParams.Length - 1, 1); jsonParams.Append(","); // Remove the opening brace. jsonParams.Append(jsonConfig); jsonParams.Append("}"); json = jsonParams.ToString(); } else { json = contentJSON; } try { VaultDataResponseObjectB vdro = await ParentVault._httpConnector.PostAsync_B(path, "VaultSystemBackend:AuthEnable", json, false); return(vdro.Success); } catch (VaultInvalidDataException e) { if (e.Message.Contains("path is already in use")) { VaultException ex = new VaultException("The authentication backend mount point already exists. Cannot enable another mount point at that location."); ex.SpecificErrorCode = EnumVaultExceptionCodes.BackendMountAlreadyExists; throw ex; } else { throw e; } } }
public async Task Auth_Enable_ConfigOptions() { string key = _uniqueKeys.GetKey("TST"); AuthMethod am = new AuthMethod(key, EnumAuthMethods.AppRole); am.Config.DefaultLeaseTTL = "120"; am.Config.MaxLeaseTTL = "240"; Assert.True(await _vaultSystemBackend.AuthEnable(am)); }
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { var request = new RestRequest(BuildUrl(), _method); SetAuthentication(request, authMethod, sessionId); request.AddParameter("ids", _userId); request.AddParameter("globalgroup", _globalGroup); return(request); }
public async Task GetPurchasedPhoneNumbers(AuthMethod authMethod) { var client = CreateClient(authMethod); var numbersPagable = client.GetPurchasedPhoneNumbersAsync(); var numbers = await numbersPagable.ToEnumerableAsync(); Assert.IsNotNull(numbers); }
public async Task <ActionResult <Auth> > Login(User user) { var authInfo = new Auth(); var u = await _context.Users.SingleOrDefaultAsync(item => item.Username == user.Username); if (u == null) { return(NotFound("Username is not existed!")); } bool verified = BCrypt.Net.BCrypt.Verify(user.Password, u.Password); if (!verified) { return(BadRequest("Incorrect Username or Password!")); } authInfo.AccessToken = AuthMethod.GenenateJSONWebToken(u, _config["Jwt:AccessTokenSecret"], Convert.ToDouble(_config["Jwt:AccessTokenExpires"]), _config["Jwt:Issuer"], _config["Jwt:Audience"]); var createNewRefreshToken = false; if (u.RefreshToken == null) { createNewRefreshToken = true; } else { var validateRefreshToken = AuthMethod.ValidateJSONWebToken(u.RefreshToken, _config["Jwt:RefreshTokenSecret"], _config["Jwt:Issuer"], _config["Jwt:Audience"]); if (validateRefreshToken == null) { createNewRefreshToken = true; } } if (createNewRefreshToken == true) { var refreshToken = AuthMethod.GenenateJSONWebToken(u, _config["Jwt:RefreshTokenSecret"], Convert.ToDouble(_config["Jwt:RefreshTokenExpires"]), _config["Jwt:Issuer"], _config["Jwt:Audience"]); u.RefreshToken = refreshToken; _context.Entry(u).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } } authInfo.RefreshToken = u.RefreshToken; authInfo.User = u; return(Ok(authInfo)); }
// Make sure that the non-JSON constructor will set the path and name value correctly. public void AuthMethod_Constructor_SetsNameAndPathCorrectly() { string path = "test2/"; string name = path.Substring(0, path.Length - 1); AuthMethod am = new AuthMethod(path, EnumAuthMethods.Kubernetes); Assert.AreEqual(path, am.Path); Assert.AreEqual(name, am.Name); }
/// <summary> /// Creates a <see cref="PhoneNumbersClient" /> based on provided authMethod /// and instruments it to make use of the Azure Core Test Framework functionalities. /// </summary> /// <returns>The instrumented <see cref="PhoneNumbersClient" />.</returns> protected PhoneNumbersClient CreateClient(AuthMethod authMethod = AuthMethod.ConnectionString, bool isInstrumented = true) { return(authMethod switch { AuthMethod.ConnectionString => CreateClientWithConnectionString(isInstrumented), AuthMethod.KeyCredential => CreateClientWithAzureKeyCredential(isInstrumented), AuthMethod.TokenCredential => CreateClientWithTokenCredential(isInstrumented), _ => throw new ArgumentOutOfRangeException(nameof(authMethod)) });
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { // authMethod and sessionId are useless, we're not logged in anyway! var request = new RestRequest(ResourceUris.Login, Method.POST); request.RequestFormat = DataFormat.Json; request.AddBody(new { username = _username, password = Utility.SecureStringToString(_password) }); return request; }
/// <summary> /// Deserializes a new instance of the ClientGreeting class from the /// specified byte array. /// </summary> /// <param name="buffer">An array of bytes to deserialize a new instance /// of the ClientGreeting class from.</param> /// <returns>An initialized instance of the ClientGreeting class.</returns> /// <exception cref="ArgumentNullException">The buffer parameter is /// null.</exception> /// <exception cref="SerializationException">The specified buffer does /// not contain a valid SOCKS5 client-greeting message.</exception> public static ClientGreeting Deserialize(byte[] buffer) { buffer.ThrowIfNull("buffer"); using (var ms = new MemoryStream(buffer)) { using (BinaryReader r = new BinaryReader(ms)) { if (r.ReadByte() != version) throw new SerializationException("Invalid SOCKS5 greeting."); byte count = r.ReadByte(); AuthMethod[] methods = new AuthMethod[count]; for (int i = 0; i < count; i++) methods[i] = (AuthMethod) r.ReadByte(); return new ClientGreeting(methods); } } }
protected void SetAuthentication(RestRequest request, AuthMethod authMethod, string sessionId) { if (String.IsNullOrEmpty(sessionId)) // Check if we have a valid id { return; } if (authMethod == AuthMethod.SessionId) { request.AddParameter(SessionIdParameterName, sessionId); } else // Cookie { request.AddCookie(SessionIdCookieName, sessionId); } }
public void Initialize(string accessToken, string accessTokenSecret, string username, long userId) { //for OAuth HttpOAuthApiProxy con = new HttpOAuthApiProxy(); if (tk != accessToken || tks != accessTokenSecret || un != username || connectionType != AuthMethod.OAuth) { // 以前の認証状態よりひとつでも変化があったらhttpヘッダより読み取ったカウントは初期化 tk = accessToken; tks = accessTokenSecret; un = username; } con.Initialize(ApplicationSettings.TwitterConsumerKey, ApplicationSettings.TwitterConsumerSecret, accessToken, accessTokenSecret, username, userId, "screen_name", "user_id"); httpCon = con; connectionType = AuthMethod.OAuth; requestToken = ""; }
public void setProtocolParams( AuthMethod authMethod, string userName, string pass, string key, bool SSH1) { // each following check can force to different authentication authMethod = this.CheckUserName(userName, authMethod); authMethod = this.CheckPublickKey(key, authMethod); authMethod = this.CheckPassword(pass, authMethod); this.AssingAuthentization(authMethod); this.ChooseProtocolVersion(SSH1); this._params.EventTracer = new SShTraceLissener(); }
/// <summary> /// Attempts to establish an authenticated session with the server using the specified /// credentials. /// </summary> /// <param name="username">The username with which to login in to the IMAP server.</param> /// <param name="password">The password with which to log in to the IMAP server.</param> /// <param name="method">The requested method of authentication. Can be one of the values /// of the AuthMethod enumeration.</param> /// <exception cref="InvalidCredentialsException">Thrown if authentication using the /// supplied credentials failed.</exception> /// <exception cref="NotSupportedException">Thrown if the specified authentication /// method is not supported by the server.</exception> /// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Login"]/*'/> public void Login(string username, string password, AuthMethod method) { string tag = GetTag(), response; switch (method) { case AuthMethod.Login: response = Login(tag, username, password); break; case AuthMethod.Auto: response = AuthAuto(tag, username, password); break; case AuthMethod.NtlmOverSspi: response = SspiAuthenticate(tag, username, password, true); break; case AuthMethod.Gssapi: response = SspiAuthenticate(tag, username, password, false); break; default: response = Authenticate(tag, username, password, method.ToString()); break; } // The server may include an untagged CAPABILITY line in the response. if (response.StartsWith("* CAPABILITY")) { capabilities = response.Substring(13).Trim().Split(' ') .Select(s => s.ToUpperInvariant()).ToArray(); response = GetResponse(); } if (!IsResponseOK(response, tag)) throw new InvalidCredentialsException(response); Authed = true; }
/// <summary> /// Initializes a new instance of the ImapClient class and connects to the specified port on /// the specified host, optionally using the Secure Socket Layer (SSL) security protocol and /// attempts to authenticate with the server using the specified authentication method and /// credentials. /// </summary> /// <param name="hostname">The DNS name of the server to which you intend to connect.</param> /// <param name="port">The port number of the server to which you intend to connect.</param> /// <param name="username">The username with which to login in to the IMAP server.</param> /// <param name="password">The password with which to log in to the IMAP server.</param> /// <param name="method">The requested method of authentication. Can be one of the values /// of the AuthMethod enumeration.</param> /// <param name="ssl">Set to true to use the Secure Socket Layer (SSL) security protocol.</param> /// <param name="validate">Delegate used for verifying the remote Secure Sockets Layer /// (SSL) certificate which is used for authentication. Set this to null if not needed</param> /// <exception cref="ArgumentOutOfRangeException">The port parameter is not between MinPort /// and MaxPort.</exception> /// <exception cref="ArgumentNullException">The hostname parameter is null.</exception> /// <exception cref="SocketException">An error occurred while accessing the socket used for /// establishing the connection to the IMAP server. Use the ErrorCode property to obtain the /// specific error code</exception> /// <exception cref="System.Security.Authentication.AuthenticationException">An authentication /// error occured while trying to establish a secure connection.</exception> /// <exception cref="BadServerResponseException">Thrown if an unexpected response is received /// from the server upon connecting.</exception> /// <exception cref="InvalidCredentialsException">Thrown if authentication using the /// supplied credentials failed.</exception> /// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="ctor-2"]/*'/> public ImapClient(string hostname, int port, string username, string password, AuthMethod method = AuthMethod.Auto, bool ssl = false, RemoteCertificateValidationCallback validate = null) { Connect(hostname, port, ssl, validate); Login(username, password, method); }
public override void Login(string userName, string password, AuthMethod method) { string response = null; switch (method) { case AuthMethod.Login: lock (sequenceLock) { response = SendCommandGetResponse("USER " + userName); if (!IsResponseOK(response)) { throw new BadServerResponseException(response); } response = SendCommandGetResponse("PASS " + password); if (!IsResponseOK(response)) { throw new InvalidCredentialsException(response); } } break; case AuthMethod.CramMD5: response = SendCommandGetResponse("AUTHENTICATE CRAM-MD5"); break; case AuthMethod.OAuth: break; } Authed = true; }
public void Initialize(string accessToken, string accessTokenSecret, string username) { //for OAuth HttpConnectionOAuth con = new HttpConnectionOAuth(); con.Initialize(ConsumerKey, ConsumerSecret, accessToken, accessTokenSecret, username, "screen_name"); httpCon = con; connectionType = AuthMethod.OAuth; }
public Task<bool> Authenticate(string Username, string PasswordOrApiKey, AuthMethod Method = AuthMethod.Password) { throw new NotImplementedException(); }
public void Login(string username, string password, AuthMethod method) { _internalClient.Login(username, password, method); }
private AuthMethod CheckPublickKey(String key, AuthMethod authMethod) { if (authMethod == AuthMethod.PublicKey) { if (string.IsNullOrEmpty(key)) return AuthMethod.Password; this.Key = SSH2UserAuthKey.FromBase64String(key).toSECSHStyle(""); } return authMethod; }
/// <summary> /// Attempts to establish an authenticated session with the server using the specified /// credentials. /// </summary> /// <param name="username">The username with which to login in to the IMAP server.</param> /// <param name="password">The password with which to log in to the IMAP server.</param> /// <param name="method">The requested method of authentication. Can be one of the values /// of the AuthMethod enumeration.</param> /// <exception cref="InvalidCredentialsException">Thrown if authentication using the /// supplied credentials failed.</exception> /// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Login"]/*'/> public void Login(string username, string password, AuthMethod method) { string tag = GetTag(); string response = null; switch (method) { case AuthMethod.Login: response = SendCommandGetResponse(tag + "LOGIN " + username.QuoteString() + " " + password.QuoteString()); break; case AuthMethod.CRAMMD5: response = SendCommandGetResponse(tag + "AUTHENTICATE CRAM-MD5"); /* retrieve server key */ string key = Encoding.Default.GetString( Convert.FromBase64String(response.Replace("+ ", ""))); /* compute the hash */ using (var kMd5 = new HMACMD5(Encoding.ASCII.GetBytes(password))) { byte[] hash1 = kMd5.ComputeHash(Encoding.ASCII.GetBytes(key)); key = BitConverter.ToString(hash1).ToLower().Replace("-", ""); string command = Convert.ToBase64String( Encoding.ASCII.GetBytes(username + " " + key)); response = SendCommandGetResponse(command); } break; case AuthMethod.SaslOAuth: response = SendCommandGetResponse(tag + "AUTHENTICATE XOAUTH " + password); break; } /* Server may include a CAPABILITY response */ if (response.StartsWith("* CAPABILITY")) { capabilities = response.Substring(13).Trim().Split(' ') .Select(s => s.ToUpperInvariant()).ToArray(); response = GetResponse(); } if (!IsResponseOK(response, tag)) throw new InvalidCredentialsException(response); Authed = true; }
/// <summary> /// Authenticates a user towards the POP server using some <see cref="AuthMethod"/>. /// </summary> /// <param name="username">The username</param> /// <param name="password">The user password</param> /// <param name="authMethod">The way that the client should authenticate towards the server</param> /// <exception cref="NotSupportedException">If <see cref="AuthMethod.Apop"/> is used, but not supported by the server</exception> /// <exception cref="InvalidLoginException">If the user credentials was not accepted</exception> /// <exception cref="PopServerLockedException">If the server said the the mailbox was locked</exception> /// <exception cref="ArgumentNullException">If <paramref name="username"/> or <paramref name="password"/> is <see langword="null"/></exception> /// <exception cref="LoginDelayException">If the server rejects the login because of too recent logins</exception> public void Authenticate(string username, string password, AuthMethod authMethod) { AssertDisposed(); if (username == null) throw new ArgumentNullException("username"); if (password == null) throw new ArgumentNullException("password"); if (State != ConnectionState.Authorization) throw new InvalidUseException("You have to be connected and not authorized when trying to authorize yourself"); switch (authMethod) { case AuthMethod.UsernameAndPassword: AuthenticateUsingUserAndPassword(username, password); break; case AuthMethod.Apop: AuthenticateUsingApop(username, password); break; case AuthMethod.Auto: if (ApopSupported) AuthenticateUsingApop(username, password); else AuthenticateUsingUserAndPassword(username, password); break; case AuthMethod.CramMd5: AuthenticateUsingCramMd5(username, password); break; } // We are now authenticated and therefore we enter the transaction state State = ConnectionState.Transaction; }
public override RestRequest CreateRestRequest(AuthMethod authMethod, string sessionId) { var request = new RestRequest(ResourceUris.Logout, Method.POST); SetAuthentication(request, authMethod, sessionId); return request; }
private AuthMethod CheckPassword(String pass, AuthMethod authMethod) { if (pass == null) pass = ""; this.Password = pass; // password always has to be set: required by grandados if (authMethod == AuthMethod.Password && pass == "") return AuthMethod.KeyboardInteractive; return authMethod; }
private void AssingAuthentization(AuthMethod authMethod) { switch (authMethod) { case AuthMethod.Password: this.AuthenticationType = AuthenticationType.Password; break; case AuthMethod.PublicKey: this.AuthenticationType = AuthenticationType.PublicKey; break; default: this.AuthenticationType = AuthenticationType.KeyboardInteractive; break; // granados doesnt support Host authentication } }
public bool Validate(string userName, string password) { NetworkCredential networkCredential = new NetworkCredential(userName, password); // empty username and password on the local box // causes authentication to succeed. If the username is empty we should just fail it // here. if (userName != null && userName.Length == 0) return false; if (_contextType == ContextType.Domain || _contextType == ContextType.ApplicationDirectory) { try { if (_lastBindMethod == AuthMethod.Simple && (_fastConcurrentSupported || _contextType == ContextType.ApplicationDirectory)) { try { BindLdap(networkCredential, defaultContextOptionsSimple); _lastBindMethod = AuthMethod.Simple; return true; } catch (LdapException) { // we don't return false here even if we failed with ERROR_LOGON_FAILURE. We must check Negotiate // because there might be cases in which SSL fails and Negotiate succeeds } BindLdap(networkCredential, defaultContextOptionsNegotiate); _lastBindMethod = AuthMethod.Negotiate; return true; } else { try { BindLdap(networkCredential, defaultContextOptionsNegotiate); _lastBindMethod = AuthMethod.Negotiate; return true; } catch (LdapException) { // we don't return false here even if we failed with ERROR_LOGON_FAILURE. We must check SSL // because there might be cases in which Negotiate fails and SSL succeeds } BindLdap(networkCredential, defaultContextOptionsSimple); _lastBindMethod = AuthMethod.Simple; return true; } } catch (LdapException ldapex) { // If we got here it means that both SSL and Negotiate failed. Tough luck. if (ldapex.ErrorCode == ExceptionHelper.ERROR_LOGON_FAILURE) { return false; } throw; } } else { Debug.Assert(_contextType == ContextType.Machine); return (BindSam(_serverName, userName, password)); } }
public abstract void Login(string userName, string password, AuthMethod method);
void DoAuthentication(AuthMethod method) { if(AuthMethod.None == method) return; if(AuthMethod.UsernamePassword == method) { SubNegotiation_UsernamePassword(); } else if(AuthMethod.NoAcceptable == method) { //throw new AuthFailedException("No acceptable methods."); throw new SocketException(SockErrors.WSAECONNREFUSED); } else { //throw invalid operation because //method is unknown and execution should be stoped proir //this point throw new InvalidOperationException("Unknown authentication requested."); } }
public void Reset() { m_nNonceCount = 1; AuthMethodsSupported = AuthMethod.Plain; FeatureTLS = false; }
/// <summary> /// /// </summary> /// <param name="stanza"></param> /// <returns></returns> public override bool NewXMLFragment(XMPPStanza stanza) { /// Looks like the crippled windows phone 7 libraries can't use output from xsd.exe, have to do this the hard way /// //XDocument doc = XDocument.Load(new StringReader(stanza.XML)); //XmlReader reader = XmlReader.Create(new StringReader(stanza.XML)); stanza.XML = stanza.XML.Replace("stream:", ""); // no support for namespaces in windows phone 7, remove them XElement xmlElem = XElement.Parse(stanza.XML); if (XMPPClient.XMPPState >= XMPPState.Authenticated) { if (xmlElem.Name == "features") return true; /// If we hit this and parse the stream featurs a second time we re-authenticate. Just return for now //if (xmlElem.Name == "stream") //{ // XMPPClient.XMPPState = XMPPState.CanBind; //} /// TODO.. see if this new stream supports bind } if (xmlElem.Name== "features") { //foreach (XElement node in xmlElem.Descendants()) //{ // System.Diagnostics.Debug.WriteLine(node.Name); //} var Mechanisms = from mech in xmlElem.Descendants("{urn:ietf:params:xml:ns:xmpp-sasl}mechanism") select new Mechanism { Name = mech.Value, }; foreach (Mechanism mech in Mechanisms) { if (mech.Name == "DIGEST-MD5") AuthMethodsSupported |= AuthMethod.MD5; else if (mech.Name == "PLAIN") AuthMethodsSupported |= AuthMethod.Plain; // else if (mech.Name == "X-GOOGLE-TOKEN") // AuthMethodsSupported |= AuthMethod.googletoken; } if (AuthMethodsSupported == AuthMethod.NotSpecified) throw new Exception("No acceptable authentication method was supplied"); var tls = xmlElem.Descendants("{urn:ietf:params:xml:ns:xmpp-tls}starttls"); if (tls.Count() > 0) FeatureTLS = true; if ((FeatureTLS == true) && (XMPPClient.UseTLS == true)) { /// Tell the man we want to negotiate TLS XMPPClient.SendRawXML(StartTLS); } else { StartAuthentication(); } return true; } else if (xmlElem.Name == "{urn:ietf:params:xml:ns:xmpp-tls}proceed") { XMPPClient.XMPPConnection.StartTLS(); /// After starting TLS, start our normal digest authentication (or plain) /// StartAuthentication(); } else if (xmlElem.Name == "{urn:ietf:params:xml:ns:xmpp-sasl}challenge") { /// Build and send response /// string strChallenge = xmlElem.Value; byte[] bData = Convert.FromBase64String(strChallenge); string strUnbasedChallenge = System.Text.UTF8Encoding.UTF8.GetString(bData, 0, bData.Length); //realm="ninethumbs.com",nonce="oFun3YWfVm/6nHCkNI/9a4XpcWIdQ5RH9E0IDVKH",qop="auth",charset=utf-8,algorithm=md5-sess //string strExampleResponse = "dXNlcm5hbWU9InRlc3QiLHJlYWxtPSJuaW5ldGh1bWJzLmNvbSIsbm9uY2U9InJaNjgreS9BeGp2SjJ6cjBCVUNxVUhQcG9ocFE4ZFkzR29JclpJcFkiLGNub25jZT0iVkdFRDNqNHUrUHE1M3IxYzNab2NhcGFzaWp1eTh2NjhoYXFzRC9IWjVKTT0iLG5jPTAwMDAwMDAxLGRpZ2VzdC11cmk9InhtcHAvbmluZXRodW1icy5jb20iLHFvcD1hdXRoLHJlc3BvbnNlPTdiM2MzOTVjZjU2MDA2Njg5MDg5MzdlYTk2YjEzZjI2LGNoYXJzZXQ9dXRmLTg="; //bData = Convert.FromBase64String(strExampleResponse); //string strUnbasedResponse = System.Text.UTF8Encoding.UTF8.GetString(bData, 0, bData.Length); //"username=\"test\",realm=\"ninethumbs.com\",nonce=\"rZ68+y/AxjvJ2zr0BUCqUHPpohpQ8dY3GoIrZIpY\",cnonce=\"VGED3j4u+Pq53r1c3Zocapasijuy8v68haqsD/HZ5JM=\",nc=00000001,digest-uri=\"xmpp/ninethumbs.com\",qop=auth,response=7b3c395cf5600668908937ea96b13f26,charset=utf-8"; if (AuthMethodUsed == AuthMethod.MD5) { string strRealm = XMPPClient.Domain; Match matchrealm = Regex.Match(strUnbasedChallenge, @"realm=""([^""]+)""", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase); if (matchrealm.Success == true) strRealm = matchrealm.Groups[1].Value; string strNonce = ""; Match matchnonce = Regex.Match(strUnbasedChallenge, @"nonce=""([^""]+)""", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline); if (matchnonce.Success == true) strNonce = matchnonce.Groups[1].Value; string strQop = "auth"; Match matchqop = Regex.Match(strUnbasedChallenge, @"qop=""([^""]+)""", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase); if (matchqop.Success == true) strQop = matchqop.Groups[1].Value; string strAlgo = "md5-sess"; Match matchalgo = Regex.Match(strUnbasedChallenge, @"algorithm=([^\s,]+)", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase); if (matchalgo.Success == true) strAlgo = matchalgo.Groups[1].Value; Random rand = new Random(); string strCnonce = rand.Next().ToString("X8").ToLower(); // Compute our MD5 response, then base64 it string strResponse = GenerateMD5Response(strAlgo, XMPPClient.UserName, XMPPClient.Domain, XMPPClient.Password, strNonce, strCnonce); string ResponseMessage = MD5Response.Replace("##RESPONSE##", strResponse); XMPPClient.SendRawXML(ResponseMessage); } else if (AuthMethodUsed == AuthMethod.Plain) { /// Send plain text stuff /// } } else if (xmlElem.Name == "{urn:ietf:params:xml:ns:xmpp-sasl}success") /// Success { XMPPClient.XMPPState = XMPPState.Authenticated; if (XMPPClient.UseTLS == true) { /// Start a new stream for some strange reason, but don't close the old one. /// OpenStreamStanza open = new OpenStreamStanza(this.XMPPClient); XMPPClient.SendRawXML(open.XML); } else { XMPPClient.XMPPState = XMPPState.CanBind; } } else if (xmlElem.Name == "{urn:ietf:params:xml:ns:xmpp-sasl}failure") /// Failed to authorize { XMPPClient.XMPPState = XMPPState.AuthenticationFailed; } return false; }
/** * */ private void SetAuthInfo(string access_token, string access_token_secret, string user_name, long user_id) { OAuthHttpConnection connection = null; //static string _cache_key = string.Empty; //static string _cache_key_secret = string.Empty; //static string _cache_user_name = string.Empty; //if ( _cache_key != access_token || _cache_key_secret != access_token_secret || _cache_user_name == user_name ) { // _cache_key = access_token; // _cache_key_secret = access_token_secret; // _cache_user_name = user_name; //} connection = this.CreateHttpConnection( access_token, access_token_secret, user_name, user_id ); this.http_connection_ = connection; this.connection_type_ = AuthMethod.OAuth; this.request_token_ = string.Empty; }
void StartAuthentication() { if ((AuthMethodsSupported & AuthMethod.MD5) == AuthMethod.MD5) { AuthMethodUsed = AuthMethod.MD5; XMPPClient.SendRawXML(MD5Auth); } else if ( ((AuthMethodsSupported & AuthMethod.Plain) == AuthMethod.Plain) && (XMPPClient.UseTLS == true)) { AuthMethodUsed = AuthMethod.Plain; byte[] bUserName = System.Text.UTF8Encoding.UTF8.GetBytes(XMPPClient.UserName); byte[] bPassword = System.Text.UTF8Encoding.UTF8.GetBytes(XMPPClient.Password); byte[] bText = new byte[2 + bUserName.Length + bPassword.Length]; bText[0] = 0; Array.Copy(bUserName, 0, bText, 1, bUserName.Length); bText[bUserName.Length + 1] = 0; Array.Copy(bPassword, 0, bText, 1+bUserName.Length+1, bPassword.Length); string strBase64Text = Convert.ToBase64String(bText); string ResponseMessage = PlainAuth.Replace("##RESPONSE##", strBase64Text); XMPPClient.SendRawXML(ResponseMessage); } // Needs some type of google token retrieved from http or something //else if (((AuthMethodsSupported & AuthMethod.googletoken) == AuthMethod.googletoken) && (XMPPClient.UseTLS == true)) //{ // AuthMethodUsed = AuthMethod.googletoken; // string strText = string.Format("\0{0}@{1}\0{2}", XMPPClient.UserName, XMPPClient.Domain, XMPPClient.Password); // byte[] bText = System.Text.UTF8Encoding.UTF8.GetBytes(strText); // string strBase64Text = Convert.ToBase64String(bText); // string ResponseMessage = PlainAuth.Replace("##RESPONSE##", strBase64Text); // XMPPClient.SendRawXML(ResponseMessage); //} }
IAsyncResult BeginDoAuthentication(AuthMethod method, AsyncCallback cb, object state) { DoAuthentication_SO stateObj = new DoAuthentication_SO(cb, state); if(AuthMethod.UsernamePassword == method) { BeginSubNegotiation_UsernamePassword( new AsyncCallback(SubNegotiation_UsernamePassword_End), stateObj); } else if(AuthMethod.NoAcceptable == method) { //throw new AuthFailedException("No acceptable methods."); throw new SocketException(SockErrors.WSAECONNREFUSED); } else if(AuthMethod.None != method) { throw new InvalidOperationException("Unknown authentication requested."); } else { stateObj.SetCompleted(); } return stateObj; }
public void Initialize(string username, string password) { //for BASIC auth HttpConnectionBasic con = new HttpConnectionBasic(); con.Initialize(username, password); httpCon = con; connectionType = AuthMethod.Basic; }
private AuthMethod CheckUserName(String userName, AuthMethod authMethod) { if (userName == null) userName = ""; this.Username = userName; if (userName == "") // can't do auto login without username return AuthMethod.KeyboardInteractive; return authMethod; }
/// <summary> /// Initializes a new instance of the ServerGreeting class. /// </summary> /// <param name="method">The authentication method to include as part of /// the greeting message.</param> public ServerGreeting(AuthMethod method) { Method = method; }