简体   繁体   中英

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

My C# REST API are called from an AngularJS web app. I secure the Web API by authenticating the user and ensuring the user is part of a specific windows group.

Now the customer would like the option of calling the API from scripts (Python). How do I implement this? Should I just get them to pass username and password as part of the json call?

If you can augment headers in Python easily, I would suggest that you use token authentication. Microsoft does not provide this type of auth directly, but via OWIN project. 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. Alternatively I think you can have the token in the cookie to maintain backwards consistency if you like.

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.

Use exactly the same authentication method you are currently using.

Here is a basic example using python (untested):

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)

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