如何使用安全?
NCache 提供两种方法来保护您的缓存并防止未经授权的访问。 NCache 集群。您可以配置 缓存节点安全性 通过 NCache 管理中心这样,连接到此节点的客户端就可以使用您在配置缓存节点安全性时提供的相同凭据访问缓存。无需更改任何代码。或者,您也可以配置安全性。 以编程方式这在以下情况下很有用: NCache 您的系统上未安装客户端,如下所示。
此外, NCache 使缓存用户能够使用以下方式安全地连接到缓存: 群组托管服务帐户 使用 (gMSA) 进行身份识别 Security 类型的属性 SecurityOptions.
硬件需求
- 安装 Alachisoft.NCache.SDK 应用程序中的 NuGet 包。
- 在您的应用程序中包含以下命名空间:
- Alachisoft.NCache。客户
- Alachisoft.NCache.Runtime.Exceptions
System.Configuration
- 添加
System.Configuration通过引用管理器进行组装。 - 缓存必须正在运行。
- 要了解 gMSA 要求,请参阅 配置 gMSA 部分。
- 有关 API 详细信息,请参阅: 缓存, 缓存连接选项, 获取缓存, 缓存管理器, 用户凭据, 使用凭据创建, CreateWithGMSA, 安全选项.
使用安全 API
此 Security 的财产 CacheConnectionOptions 该类允许您提供用户名和密码,或者使用 gMSA 进行无密码身份验证。您可以使用诸如以下的辅助方法: 使用凭据创建 or CreateWithGMSA 创建所需的配置,该配置将在缓存连接期间使用。
使用 CreateWithCredentials API 进行连接
下面的例子演示了如何使用 SecurityOptions 初始化缓存时,需要通过 API 提供用户名和密码。
try
{
string cacheName = "demoCache";
var cacheConnectionOptions = new CacheConnectionOptions();
// If the user wants to use username/password credentials, they can set the Security property to use those credentials
cacheConnectionOptions.Security = SecurityOptions.CreateWithCredentials("your-username", "your-password");
ICache cache = CacheManager.GetCache(cacheName, cacheConnectionOptions);
}
catch (ConfigurationException ex)
{
if (ex.ErrorCode == NCacheErrorCodes.SERVER_INFO_NOT_FOUND)
{
// client.ncconf must have server information
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
// Argument exception occurs in case of empty string name
}
注意:
为确保操作是故障安全的,建议处理应用程序中的任何潜在异常,如中所述 处理故障.
使用 gMSA 安全连接
以下代码示例展示了如何配置缓存连接以使用组托管服务帐户 (gMSA) 凭据进行无密码身份验证。 CreateWithGMSA().
string cacheName = "demoCache";
var cacheConnectionOptions = new CacheConnectionOptions();
cacheConnectionOptions.Security = SecurityOptions.CreateWithGMSA();
ICache cache = CacheManager.GetCache(cacheName, cacheConnectionOptions);
通过 App.config 使用凭据进行连接
以下代码示例演示了如何检索存储在安全凭据中的安全凭据。 应用配置 文件并使用以下方式应用它们 安全选项 属性。

// Initialize credentials
string userName = string.Empty;
string password = string.Empty;
string cacheName = "demoCache";
// Check if Username and Password are provided through App.config file
if (ConfigurationManager.AppSettings["Username"] != null)
{
userName = ConfigurationManager.AppSettings["Username"].ToString();
}
if (ConfigurationManager.AppSettings["Password"] != null)
{
password = ConfigurationManager.AppSettings["Password"].ToString();
}
// Use CacheConnectionOptions to provide credentials
var cacheConnectionOptions = new CacheConnectionOptions();
cacheConnectionOptions.Security = SecurityOptions.CreateWithCredentials(userName, password);
// Connect to cache with security credentials provided in App.config file
ICache cache = CacheManager.GetCache(cacheName, cacheConnectionOptions);
故障排除
Alachisoft.NCache.Runtime.Exceptions.SecurityException
如果未经授权的用户尝试执行缓存操作,或者在 GetCache() or 配置安全 in 客户端.ncconf 文件中。
解决方法
- 检查您是否通过 API 或在 客户端.ncconf. 键入错误可能是此异常的结果。
- 查看指定用户是否存在于 LDAP 中的给定域下。登录凭据必须属于托管用户登录并运行 LDAP 服务的任何服务器。