如何使用owin和Mvc 5从httpcontext获取访问令牌

Txu*_*ugo 6 c# owin asp.net-identity asp.net-mvc-5.2

我在IdentityServer 4中实现了IDP 。我的Web应用程序客户端(在Mvc 5中实现)通过IDP进行身份验证,但是现在我需要从请求中获取访问令牌。在.Net Core中执行此操作的一种方法是使用Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions类似方法:

HttpContext.Authentication.GetTokenAsync("acccess_token")
Run Code Online (Sandbox Code Playgroud)

我希望能够在我的.net Mvc5 Web应用程序客户端中执行相同的操作,但是找不到具有类似实现的任何nuget包或名称空间。能够在MVC5中而不是.net Core中执行此操作很重要。有人遇到过吗?

PS-还值得一提的是,我正在使用OpenIdConnect

Kap*_*apé 13

最近发布的4.1.0 版 Katana现在支持该SaveTokens属性(从 ASP.NET Core 向后移植)。

为了获得访问令牌:

  1. Microsoft.Owin.Security.OpenIdConnect包更新到 4.1.0(或更新版本)
  2. SaveTokens在启动类中配置:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    // Other options removed for readability
    SaveTokens = true,

    // Required for the authorization code flow to exchange for tokens automatically
    RedeemCode = true
});
Run Code Online (Sandbox Code Playgroud)
  1. 读取控制器中的访问令牌:
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];
Run Code Online (Sandbox Code Playgroud)

  • 关于为什么 Request.GetOwinContext().Authentication.AuthenticateAsync 可能返回 null 有什么建议吗?即使 SaveTokens 和 RedeemCode 设置为 true (3认同)