Get the bearer token from the OWIN Cookie and put it in API requests

Here's my scenario: I have an MVC4.5 / WebApi2 application that uses a Provider -based OpenIdConnectAuthentication Thinktecture.IdentityServer . So far I can authenticate against MVC. Now I want to authenticate to WebApi using the bearer token. Here is my config

app.UseWebApi(ConfigureAPI());
app.UseCookieAuthentication(new CookieAuthenticationOptions() {
        AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
        CookieSecure = CookieSecureOption.Always,
        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
        CookieHttpOnly = true
    });

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions() {
                EnableValidationResultCache = false,
                Authority = WebConfigurationManager.AppSettings["Authority"],
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive
            });

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions() {
                Authority = WebConfigurationManager.AppSettings["Authority"],
                ClientId = WebConfigurationManager.AppSettings["ClientId"],
                ClientSecret = WebConfigurationManager.AppSettings["ClientSecret"],
                ResponseType = "code id_token",
                Scope = "openid email profile", 
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                Notifications = new OpenIdConnectAuthenticationNotifications {
                    AuthenticationFailed = OnAuthenticationFailed,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider
                }
            };
);

      

And my WebApi config

public HttpConfiguration ConfigureAPI() {
            var httpConfig = new HttpConfiguration();
            // Configure Web API to use only bearer token authentication.
            httpConfig.SuppressDefaultHostAuthentication();
            httpConfig.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));    
            httpConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Web API routes
            httpConfig.MapHttpAttributeRoutes();

            httpConfig.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
            );
            return httpConfig;
        }

      

Since I already have an access token in my OWIN Cookie, I want to add it to the authorization header before it reaches the API and therefore get successful authentication.

Here is what I have tried

public class CustomAuthorizeAttribute : AuthorizeAttribute {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) {
            var cookies = actionContext.Request.Headers.GetCookies(".AspNet.Cookies");
            var cookie = cookies.First().Cookies.FirstOrDefault(c => c.Name == ".AspNet.Cookies");
            if (cookie != null) {               
                var unprotectedTicket = Startup.OAuthOptions.TicketDataFormat.Unprotect(ticket);
                actionContext.Request.Headers.Add("Authorization", string.Format("Bearer {0}", unprotectedTicket.Identity.Claims.First(c => c.Type == "access_token").Value));                  
            }
            return base.IsAuthorized(actionContext);
        }
    }

      

I even try to use the OWIN middleware after app.UseWebApi(ConfigureAPI());

public class UseCookieToBearerAuthentication : OwinMiddleware {
        public UseCookieToBearerAuthentication(OwinMiddleware next) : base(next) { }

        public async override Task Invoke(IOwinContext context) {
            //TODO Retrieve cookie name from somewhere like in FormsAuthentication.FormsCookieName          
            var cookies = context.Request.Cookies;
            var cookie = cookies.FirstOrDefault(c => c.Key == ".AspNet.Cookies");
            if (!cookie.Equals(default(KeyValuePair<string, string>))) {
                var ticket = cookie.Value;
                var unprotectedTicket = Startup.OAuthOptions.TicketDataFormat.Unprotect(ticket);
                context.Request.Headers.Add("Authorization", new string[]{
                    string.Format("Bearer {0}", unprotectedTicket.Identity.Claims.First(c => c.Type == "access_token").Value)
                });
            }
            await Next.Invoke(context);
        }
    }

      

So how can I achieve token authentication for my web api based on the access token in my Owin Cookie ?.

Thanks in advance.

+3


source to share


1 answer


The problem was that the IdentityServerBearerTokenAuthenticationOptions is using the default AuthenticationMode = ValidationMode.ValidationEndpoint;

, which is the default Microsoft.Owin.Security.AuthenticationMode.Active

and cannot be overridden.

So, I set IdentityServerBearerTokenAuthenticationOptions to ValidationMode = ValidationMode.Local;

and AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive;

, which is fine, because the access token is JWT (standalone).



I also use the OWIN middleware to get the access token from the cookie in the request and set it in the authorization header.

public class UseCookieToBearerAuthentication : OwinMiddleware {
        public UseCookieToBearerAuthentication(OwinMiddleware next) : base(next) { }



    public async override Task Invoke(IOwinContext context) {
                var x = Startup.OAuthOptions.CookieName;
                var cookieName = string.Format("{0}{1}", CookieAuthenticationDefaults.CookiePrefix, CookieAuthenticationDefaults.AuthenticationType);
                var cookies = context.Request.Cookies;
                var cookie = cookies.FirstOrDefault(c => c.Key == ".AspNet.Cookies");
                if (!cookie.Equals(default(KeyValuePair<string, string>))) {
                    var ticket = cookie.Value;
                    var unprotectedTicket = Startup.OAuthOptions.TicketDataFormat.Unprotect(ticket);
                    context.Request.Headers.Add("Authorization", new string[]{
                        string.Format("Bearer {0}", unprotectedTicket.Identity.Claims.First(c => c.Type == "access_token").Value)
                    });
                }
                await Next.Invoke(context);
            }
        }

      

0


source







All Articles