如何使用 owin 和 Mvc 5 从 httpcontext 获取访问令牌
How to get access token from httpcontext using owin and Mvc 5
我在 IdentityServer 4 中实现了 IDP。我的 Web 应用程序客户端(在 Mvc 5 中实现)通过 IDP 进行身份验证,但现在我需要从请求中获取访问令牌。
在 .Net Core 中做到这一点的一种方法是像这样使用 Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions
:
HttpContext.Authentication.GetTokenAsync("acccess_token")
我希望能够在我的 .net Mvc5 网络应用程序客户端中执行相同的操作,但我找不到任何具有类似实现的 nuget 包或命名空间。能够在 MVC5 而不是 .net Core 中执行此操作很重要。有人以前遇到过这个吗?
PS- 另外值得一提的是我正在使用 OpenIdConnect
在您的控制器中,您可以使用以下代码获取令牌:
var token = ActionContext.Request.Headers.Authorization.Parameter;
最近发布的 4.1.0 version of Katana now supports the SaveTokens
property(从 ASP.NET Core 向后移植)。
为了获取访问令牌:
- 将 Microsoft.Owin.Security.OpenIdConnect 软件包更新到 4.1.0(或更新版本)
- 在您的启动程序中配置
SaveTokens
class:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Other options removed for readability
SaveTokens = true,
// Required for the authorization code flow to exchange for tokens automatically
RedeemCode = true
});
- 读取控制器中的访问令牌:
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];
我花了一些时间才明白,我们需要发送一个字符串作为 AuthenticateAsync 的参数,它在 AuthenticationType 和 SignInAsAuthenticationType 中使用。
我会重新使用 CookieAuthenticationDefaults.AuthenticationType,因为它可以避免打字错误。
我在 IdentityServer 4 中实现了 IDP。我的 Web 应用程序客户端(在 Mvc 5 中实现)通过 IDP 进行身份验证,但现在我需要从请求中获取访问令牌。
在 .Net Core 中做到这一点的一种方法是像这样使用 Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions
:
HttpContext.Authentication.GetTokenAsync("acccess_token")
我希望能够在我的 .net Mvc5 网络应用程序客户端中执行相同的操作,但我找不到任何具有类似实现的 nuget 包或命名空间。能够在 MVC5 而不是 .net Core 中执行此操作很重要。有人以前遇到过这个吗?
PS- 另外值得一提的是我正在使用 OpenIdConnect
在您的控制器中,您可以使用以下代码获取令牌:
var token = ActionContext.Request.Headers.Authorization.Parameter;
最近发布的 4.1.0 version of Katana now supports the SaveTokens
property(从 ASP.NET Core 向后移植)。
为了获取访问令牌:
- 将 Microsoft.Owin.Security.OpenIdConnect 软件包更新到 4.1.0(或更新版本)
- 在您的启动程序中配置
SaveTokens
class:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Other options removed for readability
SaveTokens = true,
// Required for the authorization code flow to exchange for tokens automatically
RedeemCode = true
});
- 读取控制器中的访问令牌:
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];
我花了一些时间才明白,我们需要发送一个字符串作为 AuthenticateAsync 的参数,它在 AuthenticationType 和 SignInAsAuthenticationType 中使用。 我会重新使用 CookieAuthenticationDefaults.AuthenticationType,因为它可以避免打字错误。