IdentityModel / IdentityModel.AspNetCore.OAuth2Introspection

ASP.NET Core authentication handler for OAuth 2.0 token introspection
Apache License 2.0
146 stars 67 forks source link

Authenticate a cookie based access_token #170

Closed amccool closed 1 year ago

amccool commented 1 year ago

I have a device flow application that saves a reference_token as a cookie. I see the access_token is a opaque number, and I have a good identity_token which is then saved to a cookie SignInAync("super-duper-device") via:

.AddCookie("super-duper-device", options=>{
options.ForwardAuthenticate = "introspection";
})

.AddOAuth2Introspection("introspection") with the default tokenretriever appears to only look at the string authorization = request.Headers["Authorization"].FirstOrDefault();

I noticed there is two TokenRetrievers available FromAuthorizationHeader and FromQueryString. Neither work for my case.

Whats the correct way to get the access_token from the cookie?

amccool commented 1 year ago

Using the following TokenRetrieval

        private static AuthenticationTicket DecryptAuthCookie(HttpContext httpContext, string scheme)
        {
            var opt = httpContext.RequestServices
                .GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>()
                .Get(scheme);

            var cookie = opt.CookieManager.GetRequestCookie(httpContext, opt.Cookie.Name);

            return opt.TicketDataFormat.Unprotect(cookie);
        }

        public static Func<HttpRequest, string> FromCookie(string scheme)
        {
            return request =>
            {
                var ticket = DecryptAuthCookie(request.HttpContext, scheme);

                if (ticket.Properties.Items.ContainsKey(".Token.access_token"))
                {
                    var access_token = ticket.Properties.Items[".Token.access_token"];
                    return access_token;
                }
                else
                {
                    return null;
                }
            };
        }

with

.AddOAuth2Introspection("reference-token", options => {
                  options.TokenRetriever = yabbadappa.FromCookie(scheme: "super-duper-device");

is getting me a good opaque access_token.

So long as I am not wildly off track we can close this

leastprivilege commented 1 year ago

sure. why not ;)

amccool commented 1 year ago

when @leastprivilege replies w emojis, its safe to close the issue