Using media tokens and cookie authentication together

I have a one-page application - more or less based on the SPA MVC5 template - using authentication tokens .

The site also has some regular MVC pages that need to be protected, but using cookie authentication .

In Startup.Auth, I can enable both types of authorization:

app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOAuthBearerTokens(OAuthOptions); 

However, this seems like a side effect in that whenever an AJAX request is sent from the SPA, it sends the carrier token to the header and cookie.

While the behavior that I really want is that only the carrier token is used for WebAPI calls and only the cookie for MVC calls.

I also like MVC calls to redirect to the login page if they are not authorized (set as CookieAuthenticationOption), but obviously I do not want this to happen when the API is called.

Is there any way to authenticate mixed mode in one application? Perhaps through a path / route filter?

+57
asp.net-mvc asp.net-web-api owin
Jan 6 '14 at 15:51
source share
1 answer

I think I managed this: -

Startup.Auth connects the OWIN pipeline, so you have the right to include cookies and tokens in it. But one change in cookie settings indicates the type of authentication to which it should relate:

 CookieOptions = new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie }; 

Then I needed to configure WebAPI only to use tokens:

 public static void Configure(HttpConfiguration config) { // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); } 

This seems to achieve what I want. The WebAPI only uses media tokens and cookies, and some regular MVC pages use cookies after logging in (using the AuthenticationManager).

+42
Jan 07 '14 at 14:25
source share
β€” -



All Articles