I have a form on a template on my domain1 and want to send a POST request to domain2. I am using Django as the framework. I only want domain2 to accept requests from domain1 and domain2 (itself). However, I run into csrf problems.
You need a RESTful API. That's a very large topic and would be dumb/impossible to do the work for you here with the info I've been given, so here's a summary.
I suggest Django Rest Framework for making api's.
What the above means, is that when you want to do this sort of stuff (POST requests from other domains), you need a token. This is usually done with a Json Web Token. Also known as JWT's.
The process goes like this:
Get access token from other site to have permission to use the API from that site. Certain http headers, passwords, etc, are often included with this every single time data is exchanged.
Once you get a response giving you permission, you can now perform the type of request you want, with the data you want.
The data format for all this is USUALLY done with JSON. So you will have to import json, then json.dumps(obj) to turn it into valid json, and json.loads(obj) to turn your response into a python dictionary, so you can use it in your template, or wherever you want.
If you want to see an example of this, I recently made a free GoFundMe clone on my guthub. In the donate() view at the bottom, it uses the requests library, and shows how a JWT is obtained and used. You can see it there.
I used Django Tastypie to build my api and i'm thinking in the correct way to create a login form so the user can login in the application, right now what I do is send a GET request with username/password he submited in the form as filtering options, but i'm pretty sure thats not secure at all. How can i do the same using POST request?
When i open the console with firebug:
GET URL/app/api/v1/user/?email=USER&password=PASS
Api-Auth and Content-Type are on the header.
#leosilvano
Don't handle user authentication and authorization using angular js not that its impossible but just that its not too secure and implementing also take some effort when Django's provides something which far easy than this.
I happen to be using django + angularjs + tastypie (REST API ). If you like take a look at my way of implementation.
Include your index.html of the angularJs in your templates ( Django Templates ) and place your directives, controllers, js, css and etc in the static folder ( Django Static ). Make your API calls after the auth processes. This will work seamlessly and you will run into less issues as well.
Reasons:
user_auth models becomes so handy while registering and logging in using templates and you don't need to sweat trying to write your own authentication which i'm sure you have to do when you go with Angular Js login auth implementation.
Use of decorators like for a view lets say "profile" if you need to check if the user is logged in all you need to do it something like the following
#login_required(login_url='/login/')
def profile(request):
return render_to_response('profile.html')
Passing password through "GET" is bad .. and passing auth values through "POST" and getting it via JSON .. is also not a good idea. Because you will be susceptible to middle-man attacks ..
Remember you have to take measures for CORS requests when using Angularjs for login since anyone can view the json response and they will be able to reproduce the same structure. Implementing Perm-Mixins and Groups is way more easier when using Django templates.
Handling exceptions like 404 or if you want to handle only post requests and thereby take user to a custom page ( actions like redirect ) becomes difficult. I am aware of SPA's but still if there happens to be redirection .. in my case i needed to redirect to another site. Following shows how simple it can be achieved including http statuses.
if request.method != 'POST':
return HttpResponseNotFound(render_to_response('404.html', { 'message' : 'Only POST Requests are allowed for authentication process.', 'baseurl' :request.build_absolute_uri('/').rstrip('/')}))
Solution:
Use Angular Js and REST (Tastypie) interaction to happen after you login. Use Django template for login authorization. Make use of the django modules .. it saves a lot of time.
If you still want to login using REST API .. by send post to django .. please take a look at the following post
How can I login to django using tastypie
You can POST data using the $http module
Just do:
$http.post(url, data)
Always send authentication data through https or your password will be sent in clear text.
I'm using Django Rest Framework and Token Authentication. Everything works great so far.
http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication
But I'm realizing that anyone could create a third party app that hooks into my API. There'd be no way for me to detect it or stop it.
Am I missing something? I followed the directions, and I:
Send "username=blah&password=blah" to https://example.com/api/auth/, and receive a Token in return. Anyone could do this from a third party app.
That token is passed in the authentication header to retrieve data from the API. Anyone could do this if they have their user token.
Even if a user knows their own Token, I only want them to be able to access the API through the official native app.
1. How do I secure my API (using Token authentication) and make sure that only MY apps can connect to it?
2. Could I include some kind of secret key in a header? I'm using HTTPS in production, are headers as well as form data (username/password) interceptable/readable? (By the person running the app).
Still learning, thank you.
Perhaps I don't understand you question fully, but:
yes, everyone with a username and a password in your application can create tokens, if you added obtain_auth_token to your urlconfig (what you don't have to).
So you can:
only give your apps username and password
or deactivate the obtain_auth_token view and create the tokens in the admin or manually.
To answer your HTTPS question:
HTTPS encryption is between the client and the server and lies between TCP and HTTP. So everyone in between (a man in the middle) can't see any headers, data, or even the path. When using SNI the hostname (Host header) is visible, but nothing else.
Hope this helps a little.
I am building a web application with a services layer. The services layer is going to be built using a RESTful design. The thinking is that some time in the future we may build other applications (iPhone, Android, etc.) that use the same services layer as the web application. My question is this - how do I implement login? I think I am having trouble moving from a more traditional verb based design to a resource based design. If I was building this with SOAP I would probably have a method called Login. In REST I should have a resource. I am having difficulty understanding how I should construct my URI for a login. Should it be something like this:
http://myservice/{username}?p={password}
EDIT: The front end web application uses the traditional ASP.NET framework for authentication. However at some point in the authentication process I need to validate the supplied credentials. In a traditional web application I would do a database lookup. But in this scenario I am calling a service instead of doing a database lookup. So I need something in the service that will validate the supplied credentials. And in addition to validating the supplied credentials I probably also need some sort of information about the user after they have successfully authenticated - things like their full name, their ID, etc. I hope this makes the question clearer.
Or am I not thinking about this the right way? I feel like I am having difficulty describing my question correctly.
Corey
As S.Lott pointed out already, we have a two folded things here: Login and authentication
Authentication is out-of-scope here, as this is widely discussed and there is common agreement. However, what do we actually need for a client successfully authenticate itself against a RESTful web service? Right, some kind of token, let's call it access-token.
Client) So, all I need is an access-token, but how to get such RESTfully?
Server) Why not simply creating it?
Client) How comes?
Server) For me an access-token is nothing else than a resource. Thus, I'll create one for you in exchange for your username and password.
Thus, the server could offer the resource URL "/accesstokens", for POSTing the username and password to, returning the link to the newly created resource "/accesstokens/{accesstoken}".
Alternatively, you return a document containing the access-token and a href with the resource's link:
<access-token
id="{access token id goes here; e.g. GUID}"
href="/accesstokens/{id}"
/>
Most probably, you don't actually create the access-token as a subresource and thus, won't include its href in the response.
However, if you do so, the client could generate the link on its behalf or not? No!
Remember, truly RESTful web services link resources together in a way that the client can navigate itself without the need for generating any resource links.
The final question you probably have is if you should POST the username and password as a HTML form or as a document, e.g. XML or JSON - it depends... :-)
You don't "login". You "authenticate". World of difference.
You have lots of authentication alternatives.
HTTP Basic, Digest, NTLM and AWS S3 Authentication
HTTP Basic and Digest authentication. This uses the HTTP_AUTHORIZATION header. This is very nice, very simple. But can lead to a lot of traffic.
Username/Signature authentication. Sometimes called "ID and KEY" authentication. This can use a query string.
?username=this&signature=some-big-hex-digest
This is what places like Amazon use. The username is the "id". The "key" is a digest, similar to the one used for HTTP Digest authentication. Both sides have to agree on the digest to proceed.
Some kind of cookie-based authentication. OpenAM, for example, can be configured as an agent to authenticate and provide a cookie that your RESTful web server can then use. The client would authenticate first, and then provide the cookie with each RESTful request.
Great question, well posed. I really like Patrick's answer. I use something like
-/users/{username}/loginsession
With POST and GET being handled. So I post a new login session with credentials and I can then view the current session as a resource via the GET.
The resource is a login session, and that may have an access token or auth code, expiry, etc.
Oddly enough, my MVC caller must itself present a key/bearer token via a header to prove that it has the right to try and create new login sessions since the MVC site is a client of the API.
Edit
I think some other answers and comments here are solving the issue with an out-of-band shared secret and just authenticating with a header. That's fine in many situations or for service-to-service calls.
The other solution is to flow a token, OAuth or JWT or otherwise, which means the "login" has already taken place by another process, probably a normal login UI in a browser which is based around a form POST.
My answer is for the service that sits behind that UI, assuming you want login and auth and user management placed in a REST service and not in the site MVC code. It IS the user login service.
It also allows other services to "login" and get an expiring token, instead of using a pre-shared key, as well as test scripts in a CLI or Postman.
Since quite a bit has changed since 2011...
If you're open to using a 3rd party tool, and slightly deviating from REST slightly for the web UI, consider http://shiro.apache.org.
Shiro basically gives you a servlet filter purposed for authentication as well as authorization. You can utilize all of the login methods listed by #S.Lott, including a simple form based authentication.
Filter the rest URLs that require authentication, and Shiro will do the rest.
I'm currently using this in my own project and it has worked pretty well for me thus far.
Here's something else people may be interested in.
https://github.com/PE-INTERNATIONAL/shiro-jersey#readme
The first thing to understand about REST is that its a Token based resource access.Unlike traditional ways, access is granted based on token validation. In simple words if you have right token, you can access resources.Now there is lot of whole other stuff for token creation and manipulation.
For your first question, you can design a Restfull API. Credentials(Username and password) will be passed to your service layer.Service layer then validates these credentials and grant a token.Credentials can be either simple username/password or can be SSL certificates. SSL certificates uses the OAUTH protocol and are more secure.
You can design your URI like this-
URI for token request-> http://myservice/some-directory/token?
(You can pass Credentilals in this URI for Token)
To use this token for resource access you can add this [Authorization:Bearer (token)] to your http header.
This token can be utilized by the customer to access different component of your service layer. You can also change the expiry period of this token to prevent misuse.
For your second question one thing you can do is that you grant different token to access different resource components of your service layer. For this you can specify resource parameter in your token, and grand permission based on this field.
You can also follow these links for more information-
http://www.codeproject.com/Articles/687647/Detailed-Tutorial-for-Building-ASP-NET-WebAPI-REST
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
I have faced the same problem before. Login does not translate nicely to resource based design.
The way I usually handle it is by having Login resource and passing username and password on the parameter string, basically doing
GET on http://myservice/login?u={username}&p={password}
The response is some kind of session or auth string that can then be passed to other APIs for validation.
An alternative to doing GET on the login resource is doing a POST, REST purists will probably not like me now :), and passing in the creds in the body. The response would be the same.
I'm attempting to expose a single API call using three different authentication mechanisms: django's login_required , HTTP basic auth, and OAuth. I have decorators for all three but can't quite figure out how to have them all get along smoothly.
The required logic is to allow access to the view if any of the decorators / authentication mechanisms are valid for the user's request - basically an OR. However, if I simply include all three decorators then they all want to be satisfied before letting the request through - an AND.
What's a good way to deal with this?
I'm not sure you can. Suppose the user isn't logged in: if using login_required the server would redirect to a login form, whereas using basic auth, the server would return a 401 error page with a WWW-Authenticate response header. Which of these do you want to happen? I don't see how it could be both.