How to get access token from httpcontext using owin and Mvc 5

▼魔方 西西 提交于 2020-01-03 10:48:41

问题


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")

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- Also worth to mention that I'm using OpenIdConnect


回答1:


In your controller you can get the token using this code:

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



回答2:


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

In order to get the access token:

  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. Read the access token in your Controller:
var result = await Request.GetOwinContext().Authentication.AuthenticateAsync("Cookies");
string token = result.Properties.Dictionary["access_token"];


来源:https://stackoverflow.com/questions/46319114/how-to-get-access-token-from-httpcontext-using-owin-and-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!