问题
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:
- Update the Microsoft.Owin.Security.OpenIdConnect package to 4.1.0 (or newer)
- 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
});
- 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