Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually decode OAuth bearer token in c#

In my Web Api 2.2 OWIN based application I have a situation where I manually need to decode the bearer token but I don't know how to do this. This is my startup.cs

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
    public static UnityContainer IoC;
    public void Configuration(IAppBuilder app)
    {
        //Set Auth configuration
        ConfigureOAuth(app);

        ....and other stuff
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthProvider(IoC.Resolve<IUserService>(), IoC.Resolve<IAppSettings>())
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

In my controller Im sending the bearer token as a parameter

[RoutePrefix("api/EP")]
public class EPController : MasterController
{
    [HttpGet]
    [AllowAnonymous]
    [Route("DC")]
    public async Task<HttpResponseMessage> GetDC(string token)
    {
        //Get the claim identity from the token here
        //Startup.OAuthServerOptions...

        //..and other stuff
    }
}

How to manually decode and get the claims from the token passed as a parameter?

NOTE: I know I can send the token in the header and use [Authorize] and (ClaimsIdentity)User.Identity etc but the question is how to read the token when it's not presented in the header.

like image 582
Marcus Höglund Avatar asked Nov 25 '16 08:11

Marcus Höglund


2 Answers

Just placing this here for others that may visit in the future. Solution found at https://long2know.com/2015/05/decrypting-owin-authentication-ticket/ is simpler.

Just 2 lines :

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



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);
    } }
like image 63
Osa E Avatar answered Sep 18 '22 12:09

Osa E


I created a sample project for deserializing bearer tokens, which are encrypted using the MachineKeyDataProtector. You can take a look at the source code.

Bearer-Token-Deserializer

like image 36
Legends Avatar answered Sep 20 '22 12:09

Legends