简体   繁体   中英

Bearer and Cookie Authentication

I have two webprojects: MyApp and Api.MyApp. MyApp is an MVC5 Application and Api.MyApp is a MVC WebAPI application.

MyApp is a rich client application that calls the API project for most of its operations. For authorization I am using a Bearer token for the web api but I would also like to have a cookie so I can secure certain routes in the main MyApp MVC project.

To get the bearer token I call " http://api.myapp/token " can I throw this bearer token into a cookie and have the MVC project recognize it or do I have to send 2 separate calls, 1 to the api to get the bearer token and 1 to the mvc app to get the cookie. This seems a little redundant, is there a better way?

Yes.

Assuming your applications are responding on something like:

  • api.example.com
  • www.example.com

The user comes to your site on www.example.com and provides their credentials. Your app then makes an AJAX call to api.example.com to get the token. You have a couple of options now:

  1. api.example.com returns the token, along with a cookie, with the domain set to .example.com
  2. api.example.com returns the token, and the client-side script sets that into a cookie with the domain set to .example.com

If you do this, then both the API and the client application should have access to the cookie based token.

You may have to roll your own authorisation mechanism based on the bearer cookie if you're not using .Net auth tokens.

If however you are on intranet type domains (ie http://myapp/ and http://api.myapp ) then you'll have to go with option 2 and use the default domain for the cookie (you can't set a cookie with just a single period in the domain otherwise I could set one to ".com" and splurge data everywhere.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM