How to decrypt asp.net owin token in asp.net core manually?

2.3k Views Asked by At

I have an existing application which generates owin identity token with machine key approach. The same token is used to authenticate various application. One of the application is now in asp.net core. Is there any way to use same owin generated identity token in asp.net core?

or we can decode that token manually in asp.net core

2

There are 2 best solutions below

1
SUNIL DHAPPADHULE On

You can decrypt the Access Token returned from the authorization code flow directly by using IDataProtector. we implement the IDataProtector interface and use the System.Web.Security.MachineKey.Unprotect method. To Make helper Method to decrypt the OWIN ticket

private class MachineKeyProtector : IDataProtector
{
    private readonly string[] _purpose =
    {
        typeof(OAuthAuthorizationServerMiddleware).Namespace,
        "Access_Token",
        "v1"
    };

    public byte[] Protect(byte[] userData)
    {
        //throw new NotImplementedException();
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);
    }
}

To get ClaimsIdentity and a Dictionary of Properties. we just create an instance and pass in the Token to get the decrypted Ticket

var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);

Above AuthenticationTicket itself contains the ClaimsIdentity and a Dictionary of Properties. refer IDataProtector Interface

0
Chris Pratt On

You cannot share anything between ASP.NET and ASP.NET Core when using machine keys. The only way to be able to decrypt something in ASP.NET Core set by an ASP.NET app is if 1) the ASP.NET app(s) utilize the data protection provider 2) the data protection provider key ring is persisted to filesystem or network location accessible by all the apps (ASP.NET and ASP.NET Core alike) and all the apps utilize the same application name.

The docs go into great detail on this.