使用EWS协议读取Exchange邮件时报GSSAPI相关错

发布时间 2023-06-16 15:52:05作者: 和吾玩
  • 错误信息:GSSAPI operation failed with error
    GSSAPI operation failed with error - An unsupported mechanism was requested.NTLM authentication requires the GSSAPI plugin 'gss-ntlmssp'
  • 错误原因:
    .NET Core的默认Docker映像不包含NTLM支持包(即gss-ntlmssp)。结果,由于未在计算机上安装与NTLM相关的软件包,因此HttpClient在尝试对NTLM服务器进行身份验证时将引发异常。
  • 解决方案:
    最开始按照网上的方法,使用了下面的代码,解决了报错
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{    
    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
    Console.WriteLine("运行平台是linux");
}

但是!!只是代码运行不报错了,后面向服务器发起请求后,就一直报错401!

Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The remote server returned an error: (401) Unauthorized.

为此还以为是邮件服务器有问题,还找了微软的工程师,结果很尴尬,人家说服务器没问题,让我们找自己服务的原因,并给出了一个关键的方向:NTMLv2

要不就说人家是专业的,自己一脸懵逼的不知道啥是ntml,翻了大量的资料终于有了点头绪,这时候就恍然大悟,后知后觉的就意识到肯定跟上面的GSS报错有关系!

个人感觉应该是

  1. 我的代码想向邮件服务器发起NTML验证
  2. 服务器环境不支持NTML(缺少gss-ntlmssp),于是报错GSSAPI
    所以最终我给的解决方案就是在代码的运行环境中安装组件gss-ntlmssp。(我是在docker运行发布的),下面是Dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:3.1
COPY sources.list /etc/apt/sources.list
RUN apt-get update && apt-get install -y \
    gss-ntlmssp
COPY . /app
WORKDIR /app
EXPOSE 5000/tcp
CMD ["dotnet","ApiServer.dll","--urls=http://*:5000"]

要先换源方便安装软件,dotnet/aspnet:3.1官方镜像的基础系统是Debian10,下面是sources.list

# 中科大源

deb http://mirrors.ustc.edu.cn/debian buster main contrib non-free
deb http://mirrors.ustc.edu.cn/debian buster-updates main contrib non-free
deb http://mirrors.ustc.edu.cn/debian buster-backports main contrib non-free
deb http://mirrors.ustc.edu.cn/debian-security/ buster/updates main contrib non-free

# deb-src http://mirrors.ustc.edu.cn/debian buster main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian buster-updates main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian buster-backports main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian-security/ buster/updates main contrib non-free