尝试使用 asp.net core MVC API 检索 Windows 用户数据

问题描述 投票:0回答:1

我正在尝试检查当前用户的 Windows 凭据,以查看该用户是否可以与我的应用程序数据库中的用户匹配,如果可以,我将使用不记名令牌登录它们。我只需要查看当前登录用户的名称,仅此而已,不需要复杂的身份验证或授权,因此显然需要保留匿名身份验证。 当前无论是从 Visual Studio 还是在 IIS 上运行,用户始终为空。

我的文件:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);

app.UseAuthentication();
app.UseAuthorization();

Controller:
[HttpGet(EP_GET_WIN_USER)]
public ActionResult GetWinUser()
{
    var user = HttpContext.User;

    if(user != null)
    {
        return Ok(user);
    }
    else
    {
        return Unauthorized();
    }
}
LaunchSettings:
"iisSettings": {
  "windowsAuthentication": true,
  "anonymousAuthentication": true,

我检查了所有可用的论坛和视频,但没有成功。如果需要更多信息,请告诉我。

iis asp.net-core-mvc windows-authentication
1个回答
0
投票

您可以尝试以下方法:
安装包

Microsoft.AspNetCore.Authentication.Negotiate

在program.cs中使用
NegotiateDefaults.AuthenticationScheme
:

// remove "builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme)"
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

在控制器操作之上,您可以添加具有特定方案的

Authorize
属性

    [Authorize(AuthenticationSchemes = NegotiateDefaults.AuthenticationScheme)]
    [HttpGet(EP_GET_WIN_USER)]
    public ActionResult GetWinUser()
    {
        var user = HttpContext.User;

        ...
    }

然后

"windowsAuthentication": true,
将适用于视觉工作室。如果您启用 Windows 身份验证,IIS 也可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.