简体   繁体   English

承载和Cookie身份验证

[英]Bearer and Cookie Authentication

I have two webprojects: MyApp and Api.MyApp. 我有两个Web项目:MyApp和Api.MyApp。 MyApp is an MVC5 Application and Api.MyApp is a MVC WebAPI application. MyApp是MVC5应用程序,而Api.MyApp是MVC WebAPI应用程序。

MyApp is a rich client application that calls the API project for most of its operations. MyApp是一个富客户端应用程序,它为大多数操作调用API项目。 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. 为了获得授权,我在Web api上使用了Bearer令牌,但我也想拥有一个cookie,以便可以保护MyApp MVC主项目中的某些路由。

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. 要获取承载令牌,我可以调用“ http://api.myapp/token ”,我可以将此承载令牌放入cookie并让MVC项目识别它,还是必须发送2个单独的调用,其中1个要发送给api才能获取承载令牌和1到mvc应用程序以获取cookie。 This seems a little redundant, is there a better way? 这似乎有点多余,是否有更好的方法?

Yes. 是。

Assuming your applications are responding on something like: 假设您的应用程序对以下内容做出响应:

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

The user comes to your site on www.example.com and provides their credentials. 用户访问了您在www.example.com上的网站并提供了凭据。 Your app then makes an AJAX call to api.example.com to get the token. 然后,您的应用将对api.example.com进行AJAX调用以获取令牌。 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 api.example.com返回令牌以及cookie,其域设置为.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 api.example.com返回令牌,客户端脚本将其设置为域设置为.example.com的cookie。

If you do this, then both the API and the client application should have access to the cookie based token. 如果执行此操作,则API和客户端应用程序都应有权访问基于cookie的令牌。

You may have to roll your own authorisation mechanism based on the bearer cookie if you're not using .Net auth tokens. 如果不使用.Net身份验证令牌,则可能必须基于承载cookie滚动自己的授权机制。

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.) 但是,如果您使用的是Intranet类型的域(即http://myapp/http://api.myapp ),则必须使用选项2,并将默认域用于Cookie(您无法设置Cookie,该域名在域中只有一个句点,否则我可以将其设置为“ .com”并在各处散布数据。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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