使用Opc.Ua Foundation库连接无安全级别OPC UA服务器遇身份类型错误
问题:连接安全级别为None的OPC UA服务器时出现身份类型不支持错误
连接安全级别设为None的OPC UA服务器时,抛出以下错误:
System.AggregateException: 'One or more errors occurred. (Endpoint does not support the user identity type provided.)'
现有代码
// Generate a client application ApplicationInstance application = new ApplicationInstance(); application.ApplicationType = ApplicationType.Client; // Load the configuration file application.LoadApplicationConfiguration(@"path_to_file.xml", false).Wait(); ApplicationConfiguration m_configuration = application.ApplicationConfiguration; // Get the endpoint EndpointDescription endpointDescription = new EndpointDescription("opc.tcp://192.168.0.213:4840/"); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // Create the session _uaSession = Session.Create( m_configuration, endpoint, false, false, m_configuration.ApplicationName, (uint)m_configuration.ClientConfiguration.DefaultSessionTimeout, new UserIdentity(), null) .Result;
排查与解决方法
错误原因
当OPC UA服务器安全策略为None时,绝大多数情况下仅支持匿名身份验证。你当前传入的new UserIdentity()会默认使用非匿名身份类型(如用户名密码),与服务器支持的身份类型不匹配,因此触发错误。
修复步骤
显式使用匿名身份
在创建Session时,将UserIdentity参数替换为匿名身份:// 使用匿名身份创建会话 _uaSession = Session.Create( m_configuration, endpoint, false, false, m_configuration.ApplicationName, (uint)m_configuration.ClientConfiguration.DefaultSessionTimeout, UserIdentity.Anonymous, // 替换为匿名身份 null) .Result;也可以显式指定匿名令牌类型:
new UserIdentity(UserTokenType.Anonymous)验证客户端配置
检查加载的客户端配置文件(path_to_file.xml),确保其中的UserTokenPolicy包含Anonymous类型,示例配置片段:<UserTokenPolicies> <UserTokenPolicy TokenType="Anonymous" PolicyId="Anonymous"/> </UserTokenPolicies>优化调用方式
避免直接使用.Result阻塞调用(可能导致死锁),建议改用async/await模式:_uaSession = await Session.Create( m_configuration, endpoint, false, false, m_configuration.ApplicationName, (uint)m_configuration.ClientConfiguration.DefaultSessionTimeout, UserIdentity.Anonymous, null);
内容的提问来源于stack exchange,提问作者andboz
相关产品推荐
相关产品推荐

