【问题标题】:How to get access token from httpcontext using owin and Mvc 5如何使用 owin 和 Mvc 5 从 httpcontext 获取访问令牌
【发布时间】:2018-03-01 08:11:29
【问题描述】:

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

HttpContext.Authentication.GetTokenAsync("acccess_token")

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

PS- 另外值得一提的是我正在使用 OpenIdConnect

【问题讨论】:

  • 你能用下面的答案解决吗?
  • 抱歉,这个问题我很久以前就发过,忘了选择哪个解决方案了。

标签: c# asp.net-identity owin asp.net-mvc-5.2


【解决方案1】:

在您的控制器中,您可以使用以下代码获取令牌:

var token = ActionContext.Request.Headers.Authorization.Parameter;

【讨论】:

  • 你能围绕这个添加一些上下文吗?
【解决方案2】:

最近发布的4.1.0 version of Katana 现在支持SaveTokens property(从 ASP.NET Core 向后移植)。

为了获得访问令牌:

  1. Microsoft.Owin.Security.OpenIdConnect 包更新到4.1.0(或更高版本)
  2. 在您的 Startup 类中配置 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
});
  1. 在控制器中读取访问令牌:
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];

【讨论】:

  • 关于为什么 Request.GetOwinContext().Authentication.AuthenticateAsync 可能返回 null 的任何建议?即使 SaveTokens 和 RedeemCode 设置为 true
  • @kape - 这可以在 .Net 框架 4.7.1 上运行吗?我已经关注并设置了以上属性,但中间件仍然不会自动兑换代码。请在这里查看我的问题:stackoverflow.com/questions/59965137/…
  • +1 访问 access_token 的方式多么可怕而复杂。半打 SO 链接,以及我在一天内无法处理的更多 Microsoft 文档,这是我找到的读取未加密 access_token 的解决方案?谢谢!我需要将其传递给 Graph API。这也适用于 HttpContext。 HttpContext.Current.GetOwinContext().Authentication.AuthenticateAsync("Cookies")
  • 发布 .NET CORE 解决方案的链接。 stackoverflow.com/a/50623141/2567273
  • @Hos 我找到了解决方案。我认为您在 SignInAsAuthenticationType 或 AuthenticationType 中打错字,因为使用“Cookies”不起作用。
【解决方案3】:

在我理解之前我花了一些类型,我们需要发送一个字符串作为 AuthenticateAsync 的参数,该参数用于 AuthenticationType 和 SignInAsAuthenticationType。 我建议使用 CookieAuthenticationDefaults.AuthenticationType 因为它可以让你避免打字错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2018-09-20
    • 1970-01-01
    • 2017-09-26
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多