Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 328
Txugo Avatar asked Sep 20 '17 10:09

Txugo


2 Answers

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"];
like image 115
Kapé Avatar answered Nov 10 '22 02:11

Kapé


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

var token = ActionContext.Request.Headers.Authorization.Parameter;
like image 1
Victor Hugo Terceros Avatar answered Nov 10 '22 02:11

Victor Hugo Terceros