Search code examples
c#asp.net-identityowinasp.net-mvc-5.2

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


Solution

  • 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"];