gpt4 book ai didi

c# - 如何使用 Identity Server 4 基于 Windows 身份验证颁发访问 token

转载 作者:行者123 更新时间:2023-12-04 07:13:31 24 4
gpt4 key购买 nike

我的目标是保护 Web API,以便客户端只能使用 IS 基于 Windows 身份验证发布的访问 token 来访问它。我完成了这个基本示例:
http://docs.identityserver.io/en/release/quickstarts/1_client_credentials.html

现在,我需要扩展基本示例,以便返回给客户端的访问 token 是基于 Windows 身份验证发出的。更具体地说,我需要让用户(正在执行客户端应用程序)在请求访问 token 时针对 Active Directory 进行身份验证。这应该怎么做?

我已经成功运行了快速启动(https://github.com/IdentityServer/IdentityServer4.Templates),其中登录基于 Windows 外部提供程序,但我不知道如何在我的策略中采用此功能。

我尝试使用扩展授权 ( http://docs.identityserver.io/en/release/topics/extension_grants.html ) 并使用 ValidateAsync() 方法对 AD 进行身份验证,但无法使其工作(主要是因为 HttpContext 不可用)。这甚至是正确的方法吗?

更新

在这个系统中,客户端是一个控制台应用程序(没有人工交互),因此上下文是运行应用程序的帐户。
我一直在运行 QuickstartUI 并查看 AccountController 逻辑如何处理“Windows”按钮,但无法掌握如何将其与请求访问 token 结合起来。我的客户端代码是这样的:

static async Task Main(string[] args)
{
var disco = await DiscoveryClient.GetAsync("http://localhost:50010");

var tokenClient = new TokenClient(disco.TokenEndpoint);
var tokenResponse = await tokenClient.RequestCustomGrantAsync("CustomWindows"); // Not sure about this

var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);

var response = await client.GetAsync("http://localhost:50011/api/identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));

Console.ReadLine();
}

在这种情况下,我不确定如何使用 TokenClient 获取访问 token 。我宁愿不存储和使用密码,而是让 IS 根据针对 AD 的客户端上下文进行身份验证来发出访问 token 。如果在这种情况下必须使用隐式或混合流,那么必须如何完成?

最佳答案

我有同样的要求,并使用延期补助金实现了它。
这是扩展授权的代码:

public class WinAuthGrantValidator : IExtensionGrantValidator
{
private readonly HttpContext httpContext;

public string GrantType => WinAuthConstants.GrantType;

public WinAuthGrantValidator(IHttpContextAccessor httpContextAccessor)
{
httpContext = httpContextAccessor.HttpContext;
}

public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
// see if windows auth has already been requested and succeeded
var result = await httpContext.AuthenticateAsync(WinAuthConstants.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
context.Result = new GrantValidationResult(wp.Identity.Name, GrantType, wp.Claims);
}
else
{
// trigger windows auth
await httpContext.ChallengeAsync(WinAuthConstants.WindowsAuthenticationSchemeName);
context.Result = new GrantValidationResult { IsError = false, Error = null, Subject = null };
}
}
}

这是客户端代码:
var httpHandler = new HttpClientHandler
{
UseDefaultCredentials = true,
};

// request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret", httpHandler, AuthenticationStyle.PostValues);
var tokenResponse = await tokenClient.RequestCustomGrantAsync("windows_auth", "api1");

关于c# - 如何使用 Identity Server 4 基于 Windows 身份验证颁发访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48700458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com