You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net下WebSocketSharp服务器WSS安全配置错误排查及正确配置方法

问题:WebSocketSharp服务器WSS配置引发SSPI认证异常

服务器端代码如下:

Public Shared Sub Start(Port As Integer)
    ws = New WebSocketServer(Port, True)

    Dim filename As String = "cert.pfx"
    Dim cert As New Security.Cryptography.X509Certificates.X509Certificate2(filename, "pass123", Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet)

    With ws.SslConfiguration
        .ServerCertificate = cert
        .ClientCertificateRequired = False
        .CheckCertificateRevocation = False
        .ClientCertificateValidationCallback = Function() As Boolean
                                                   Return True
                                               End Function
        .EnabledSslProtocols = Security.Authentication.SslProtocols.Tls12
    End With

    ws.AddWebSocketService(Of GameBehavior)("/Game")
    ws.Start()
End Sub

应用启动无报错,但客户端通过wss协议连接时抛出以下异常:

2022年9月1日 下午6:08:54
|致命|<>c__DisplayClass71_0.b__0:0|System.Security.Authentication.AuthenticationException:
调用SSPI失败,请查看内部异常。 --->
System.ComponentModel.Win32Exception: 处理证书时发生未知错误

使用ws非安全模式启动则完全正常,请问WSS配置哪里出错?如何正确配置?


原因分析及解决方案

1. 证书路径问题

你使用的cert.pfx是相对路径,程序启动时可能无法定位到该文件。确保证书文件存在于程序工作目录,或者改用绝对路径加载:

Dim filename As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cert.pfx")

2. 证书密钥存储权限问题

使用MachineKeySet标志时,程序需要足够权限访问机器级证书存储。若以普通用户权限运行程序,建议改用UserKeySet组合标志:

Dim cert As New X509Certificate2(filename, "pass123", X509KeyStorageFlags.UserKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)

添加PersistKeySet和Exportable可避免密钥加载时的权限限制问题。

3. 证书有效性问题

  • 检查cert.pfx是否损坏:用Windows证书管理器打开文件,输入密码后确认能正常查看证书详情。
  • 确认证书包含私钥:PFX文件必须包含私钥才能用于SSL/TLS认证,仅含公钥会触发SSPI错误。
  • 验证证书用途:查看证书的「增强型密钥用法」,确保包含「服务器身份验证」(OID 1.3.6.1.5.5.7.3.1)。

4. SSL配置冗余问题

在不需要客户端证书验证的场景下,可省略ClientCertificateValidationCallback配置,避免不必要的逻辑干扰。同时可尝试兼容更多TLS协议版本测试:

With ws.SslConfiguration
    .ServerCertificate = cert
    .ClientCertificateRequired = False
    .CheckCertificateRevocation = False
    .EnabledSslProtocols = Security.Authentication.SslProtocols.Tls12 Or Security.Authentication.SslProtocols.Tls13
End With

5. 程序运行权限问题

Windows系统下,尝试以管理员身份运行程序,部分证书操作需要更高权限才能完成。


验证步骤

  1. 优先确认证书路径正确性,改用绝对路径加载。
  2. 更换密钥存储标志为UserKeySet组合,测试是否解决问题。
  3. 检查证书完整性和用途,确保符合SSL服务器要求。

内容的提问来源于stack exchange,提问作者Wolfgang Amadeus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:54:26