简体   繁体   English

安全地将C#REST API暴露给Python等脚本语言

[英]Securely Exposing C# REST API to scripting language such as Python

My C# REST API are called from an AngularJS web app. 我的C#REST API是从AngularJS Web应用程序调用的。 I secure the Web API by authenticating the user and ensuring the user is part of a specific windows group. 我通过验证用户并确保用户是特定Windows组的一部分来保护Web API。

Now the customer would like the option of calling the API from scripts (Python). 现在,客户希望从脚本(Python)调用API。 How do I implement this? 我该如何实现? Should I just get them to pass username and password as part of the json call? 我应该让他们通过用户名和密码作为json调用的一部分吗?

If you can augment headers in Python easily, I would suggest that you use token authentication. 如果你可以轻松地在Python中扩充标题,我建议你使用令牌认证。 Microsoft does not provide this type of auth directly, but via OWIN project. Microsoft不直接提供此类auth,而是通过OWIN项目提供。 It's not that hard to use, but you'll need to learn how stuff works first. 这并不难,但你需要先了解它的工作原理。 There is a very good and comprehensive tutorial here . 有一个很好的和全面的教程在这里

Basically you obtain a token (that is valid for some period of time) by providing a username/password. 基本上,您通过提供用户名/密码来获取令牌(在一段时间内有效)。 This token is encrypted/signed which means your backend will trust is without the need of validating username/password on each request (which is costly). 此令牌已加密/签名,这意味着您的后端将信任,无需在每个请求上验证用户名/密码(这是昂贵的)。 Then you need to add this token to a header Authorization bearer token or something similar for each request. 然后,您需要将此标记添加到标头Authorization bearer token或类似的每个请求。 Alternatively I think you can have the token in the cookie to maintain backwards consistency if you like. 或者,我认为如果您愿意,可以在cookie中使用令牌以保持向后一致性。

I would suggest that you use the same mechanism in Angular as well, since you can easily add an interceptor there and avoid cookies and CSRF potential troubles with them. 我建议您在Angular中使用相同的机制,因为您可以轻松地在那里添加拦截器并避免使用cookie和CSRF潜在的麻烦。

Use exactly the same authentication method you are currently using. 使用与您当前使用的完全相同的身份验证方法。

Here is a basic example using python (untested): 这是使用python(未经测试)的基本示例:

from requests.auth import HTTPBasicAuth
s = requests.Session()

# Make the initial authentication request from a session object
s.get('https://omg.wtf/user', auth=HTTPBasicAuth('user', 'pass'))

# All subsequent requests from that session will include any cookies set in the initial response
r = s.get('http://omg.wtf/911')
print(r.text)

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

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