VSCode Rest Client访问Windows认证的ASP.NET Core接口遇401未授权
ASP.NET Core Windows认证:Rest Client返回401的解决办法
问题重现
开发的ASP.NET Core Web应用采用Windows认证(Negotiate方案),浏览器访问/MapGetTest端点正常,但使用VSCode Rest Client扩展测试时返回401未授权:
GET https://localhost:7264/test
HTTP/1.1 401 Unauthorized
Content-Length: 0
Connection: close
Date: Thu, 27 Apr 2023 16:07:44 GMT
Server: Kestrel
WWW-Authenticate: Negotiate
相关代码:
test.rest
GET https://localhost:7077/MapGetTest HTTP/1.1
program.cs
using Microsoft.AspNetCore.Authentication.Negotiate; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) .AddNegotiate(); builder.Services.AddAuthorization(options => { // By default, all incoming requests will be authorized according to the default policy. options.FallbackPolicy = options.DefaultPolicy; }); builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.MapGet("/MapGetTest",() => { return "Hello World"; }); app.Run();
解决方法
1. 全局开启Rest Client Windows认证(推荐)
打开VSCode设置,搜索rest-client.enableWindowsAuth,勾选启用该选项。之后所有Rest Client请求都会自动携带当前Windows登录用户的凭据,完成Negotiate认证流程。
2. 单个请求添加认证头
如果无需全局配置,可在.rest请求中手动指定认证方式:
GET https://localhost:7077/MapGetTest HTTP/1.1 Authorization: Negotiate
或者使用NTLM认证:
GET https://localhost:7077/MapGetTest HTTP/1.1 Authorization: NTLM
原因
浏览器会自动处理Windows认证的Negotiate/NTLM握手流程,自动附加当前用户凭据。而VSCode Rest Client默认不会主动发送这些凭据,因此服务器返回401并要求进行Negotiate认证。
内容的提问来源于stack exchange,提问作者w.storey
相关产品推荐
相关产品推荐

