如何使用owin和Mvc 5从httpcontext获取访问令牌 [英] How to get access token from httpcontext using owin and Mvc 5

查看:354
本文介绍了如何使用owin和Mvc 5从httpcontext获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a IDP implemented in IdentityServer 4. My web app client(implemented in Mvc 5) authenticates with the IDP but now I need to get the access token from the request. A way to do that in .Net Core is to use the Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions like so:

HttpContext.Authentication.GetTokenAsync("acccess_token")

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

I would like to be able to do the same in my .net Mvc5 web app client but I can't find any nuget package or namespace that has a similar implementation. It is important to be able to do this in MVC5 and not .net Core. Anyone came across this before?

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

PS- Also worth to mention that I'm using OpenIdConnect

推荐答案

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

The recently released 4.1.0 version of Katana now supports the SaveTokens property (backported from ASP.NET Core).

为了获取访问令牌:

  1. 更新 Microsoft.Owin.Security.OpenIdConnect 打包到4.1.0(或更高版本)
  2. 在启动类中配置SaveTokens:
  1. Update the Microsoft.Owin.Security.OpenIdConnect package to 4.1.0 (or newer)
  2. Configure SaveTokens in your Startup 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
});

  1. 在控制器中读取访问令牌:

var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];

这篇关于如何使用owin和Mvc 5从httpcontext获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆