Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
Robben_Ford_Fan_boy Avatar asked Oct 29 '16 00:10

Robben_Ford_Fan_boy


2 Answers

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.

like image 74
Ilya Chernomordik Avatar answered Sep 21 '22 23:09

Ilya Chernomordik


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)
like image 33
Sir Crusher Avatar answered Sep 22 '22 23:09

Sir Crusher