Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

asp.net mvc - Using bearer tokens and cookie authentication together

I have a single page app - more or less based on the MVC5 SPA template - using bearer tokens for authentication.

The site also has a couple of conventional MVC pages which need to be secured, but using cookie authentication.

In Startup.Auth I can enable both types of authorisation:

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

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

Whereas the behaviour I really want is that only the bearer token is used for WebAPI calls, and only the cookie for MVC calls.

I'd also like the MVC calls to redirect to a login page when not authorised (set as a CookieAuthenticationOption), but obviously I don't want this to happen when making an API call.

Is there some way to have this type of mixed-mode authentication within one application? Perhaps through a path/route filter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think I worked this out:-

Startup.Auth is wiring up the OWIN pipeline, so it is right to include Cookies and Tokens there. But one change to the cookie options specifies the authentication type it should apply to:

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

Then I needed to configure WebAPI to only 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. WebAPI just uses bearer tokens and no cookies, and a few conventional MVC pages use cookies once logged in (using the AuthenticationManager).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...