how to use Authentication in django with prodection - django

I am using django JWT for permission and rest_framwork.
there is one question. if one user uploads one post and wants to modify/delete post OR wants to change own's profile,
definitely user requests restAPI. and in the http(s) request maybe there is some information about user,
like "localhost:8000/data/change/userid/" OR exists in post body.
point is i think if someone(like hackers) catch others id(or ID number) and pretending them
server doesn't know that who is real owner does it?
how can i protect or encrpt?

Since you are using JWT, you should have a token for every request with JWT permission. So without the token, the whole system wouldn't work. As far as I can understand, you are assuming that somebody in the middle would grab some ID related to the user but that doesn't important because he wouldn't enter the system only by id!
Furthermore, whenever you are using this under HTTPS, the token is safe too. (because no one can in the middle grab it without encryption )

Related

Can a user barge into django server as another user and perform operatn if he changes info in the frontend if we are using session authentication?

Hey guys I am confused and was thinking about this problem for sometime now, I am storing the current user's username in the session storage, and I have another page in which I use the stored username for an api call, it can be any requests.
Eg. a post can be deleted by its author only, suppose, the url is api/<slug>/delete and in the frontend I have enabled the delete button only for the corresponding user, what if he edits the front end page and changes it to his username or what if I use the stored username to check that condition?
And if he sends a delete request successfully from the frontend, does the django server able to determine that the user in the current session is not the real owner and has tweaked it in the frontend?
Ps. This might be a foolish question, but I am a beginner and quite confused.
Thanks.
Naturally, we would need some code to answer your question.
Will the following delete some other user's data?
A user passes a username from the client to the server
SomeModel.objects.filter(username=username).delete()
Will the above delete the user data whose username is what has been passed from the client? Yes.
You need to always verify and validate data and permissions on the server, and also you should consider using CRUD operations on the current authenticated user (since you are working with sessions), so you don't have to send the current user' username from client, if they are logged in, that can be validated with their session.
I'd advise you to read a little more on Authentication, sessions, ect. authentication in Django
Also, I see you are using A RESTful API, so I would strongly recommend using DRF

Trying to implement a passwordless authentication using Redis and random tokens

I want to implement a passwordless email based authentication (like in medium.com!), now I want to verify if this logic flow is secure or not:
User submits his email
Server generates a random token, sets to Redis a new value where the KEY is the token, the VALUE is the email or the corresponding user id, also make the key expires within an hour or some soon future value (within tens of minutes or hours), send a link including the token to the user email (i.e. example.com/login/token/{TOKEN})
User visits his inbox and press on that link
Server checks for {TOKEN} key, if it exists, authenticate the user and redirect to homepage, if not redirect to some error page.
Is this approach secure, is there something hidden I can't figure out yet?
Also Note that this method authenticate the user with only GET methods.
I use Django/Python, so if there is some package doing that, what is it?
Also is it relevant and secure for new user registrations/password-change/other user checks? Is there impact in case of DDoS attacks like making my server spam random emails, consuming the server using having a big Redis memory consumption in short time?
For token generation, I will use some value generated by random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789')
long enough to be hard to guess ( 60-80 characters) and it is valid for a short time like I mentioned.
Yes, I have used it in production quite successfully at my company. However, the use case is a bit different, as we use it for inter-service authentication once user has logged in using the password.
Spamming of random email addresses using your service is quite a real possibility in this scheme and you would have to put in checks like Captcha etc. to ensure this does not happen.
For actual implementation refer to this link:
Is there a way to configure Django Rest Framework to store token information in Redis rather than the Database?

Advice how to implement a simple user login and authenication

We are in the process of building a simple Android application together with a simple back-end web server to allow the user to get some information form the server.
We need to login the user, to make sure he is authorized to view the data, but apart form that I do not think we have particular security concerns.
I need some advice on how we can implement the server to keep things as simple as possible.
For example, we could use something like this to make sure the user is authorized to see the data:
http://ourwebservice/user/password/viewsuchandsuchdata
Is that a good way of doing things?
Do you have any suggestions or comments?
There are many ways to secure web-services.
The simplest is possible "Basic Auth" (http://en.wikipedia.org/wiki/Basic_access_authentication). On every request, you send the user credentials in the "Authorization" HTTP header concatenated with ":" and base 64 encoded. To keep it safe, you need to make sure the connection to your web-server is using SSL (HTTPS), otherwise the user password could be intercepted.
Another "newer" solution is OAuth2, and in your case the "Resource Owner Credentials" flow. Instead of passing the user credentials on every request, you use them once to "exchange" them for a short-lived access token issued by your server. Then on any request to the web-service you pass that access token in lieu of authentication. The server must then verify that the token is valid and find out for which user it was issued. For more info see this article: http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified.
There are potentially many more "custom" ways of doing authentication...
Going the OAuth2 flow is probably more difficult but there are lots of open-source libraries out there to help you build a OAuth2 provider (http://oauth.net/2/). The advantage is that you don't have to store the user password on the device, which is safer (the less you touch passwords, the better).

OAuth2 User Mapping and Loosing my Cookies

Wrapping my old-fashioned head around OAuth....
Aside from the request/response mechanics and the Authorize / Authenticate round trips (which I think I underdstand) I am struggling with mapping my MyUser object (whatever that may contain) to an OAuth token, if (actually when, not if) the user kills any cookies (encrypted or otherwise) I may have dropped on the browser.
I get MyUser info at the original Login (call it 'registration' for my site) but now MyUser comes back, all cookies are gone so he is just 'user'. Fair enough, user has to do an OAuth login again, but now I have no way of associating the new Token / Secret with MyUser data.
What am I missing?
--- edit Aug 2/2012 -----
Let me restate this (I am pretty sure I am being thick about this but guess thats what here is for):
As pointed out in Replies, each OAuth provider has their own mechanism. We can navigate those and get back an access Token for the user.
Lets say Hero registers on my site using Facebook. FB returns his FB UserID and Name along with the Access Token. We are clever enough to request and get his FB Email, and we ask him some other registration q's before letting him in. Then we save this in our datastore (linked to our own User record):
OurUserId : 1234
oAuthProviderName : Facebook
oAUthProviderUserId: xxxxx
oAuthProviderUserEmail: hero#mlb.com
oAuthProviderUserName: iBeHero
oAuthToken: entracingly-unique-string-of-goop
oAuthSecret: moredata
.... etc.
and set a cookie to identify him as our user# 1234.
Now Hero goes away, kills his cookies for some reason, and then comes back to us.
Now he decides to Log In with Twitter. I have no cookie so I don't know who he is, and we go through the process again.
To me he looks like a new user so once Twitter sends me a Token I start asking him Registration questions, clearly not right.
Turns out Twitter doesn't return an Email address so I can't match that, and even if they did (I think almost everyone else does) Hero likley has more than one Email.
It seems to me that the only tie I have between the two (or however many) logins is whatever cookies I set that have not been deleted.
Are we saying that the entire OAuth2.0 mechanism hangs on this? I can't belive that is right, but don't see another way, so I must be missing something , yes?
If you're using OAuth as a login mechanism as well, then make sure whichever provider you're talking to has some way of returning back a stable ID for a user. That ID is the key you'd use for looking up the user in your DB.
Different providers have different ways of doing this. For Google, details on how to do authentication with OAuth 2.0 are here. For Twitter, they use OAuth 1.0 and return the user ID when exchanging the code for an access token. Facebook has its own way of doing it as well.

jax-rs rest webservice authentication and authorization

I have a web application that needs to allow users using different webclients (browser, native mobile app, etc) to register. After signing in they can access restricted content or their own content (like entries they create, etc).
What I did so far: I created a jax-rs rest webservice (I'm hosting my application on glassfish) that exposes the following methods:
register - user POST's his desired username/password/email/etc; if username/email is unique, an entry for this user is created in the database (I'm using Hibernate for persistence)
login - user POST's username and password. If they are ok a UUID is created and returned to the user (this will be used as a token for future requests). I have a table called logedusers, with userID, token, validSince as columns.
Here is where it gets confusing for me.
Let's say that I have another method, getUserEntries, that should return all the entries made by the user. To make this clearer, there will be a Entry table with the following fields: entryId, userId, text.
What is the best approach here?
What i do now, is I make a get request and pass in the token like this:
localhost:8080/myApp/getUserEntries?token=erf34c34
Afterwards, if the token is valid, I get the userID from the logedusers table and based on that userId, get all the entries and return them as json.
Something like this:
#GET
#Path("getUserEntries")
#Produces(MediaType.APPLICATION_JSON)
public Response getUserEntries(#QueryParam("token") String token) {
String userId=getUserIdFromToken(token);
if (userId == null){
return Response.status(Response.Status.UNAUTHORIZED).build();
} else {
//get some data associated with that userId, put it in the response object and send it back
return Response.ok().entity(response).build();
}
}
However, what happens if I have more methods that provide data if they are called by a valid user?
I'd have to do this check at the beginning of every method.
I want to make this authorization process transparent
So, two major questions here:
Is this design ok? The whole authenticate with user/pass, server creates and stores and sends token to the user, user sends token on future requests.
What do I do if i have many endpoints that need to determine the identity of the calling user? Can I mark them with some annotations, use some sort of security provider / authenticator (where I can add my own logic for validating - eg check to see if the token isn't older than 5 days, etc).
Thanks
Is this design ok? The whole authenticate with user/pass, server creates and stores and sends token to the user, user sends token on future requests.
It's somewhat OK. The conceptual level isn't too bad (provided you're OK with self-registration at all) but the interface needs a lot of tweaking. While yes, POST to register and login is correct, for the rest of your webapp you should be pulling the identity information out of the context if you need it, and using role-based access control at the method level where you can.
Note that your container has a whole set of authentication and authorization-support mechanisms built in. Use them.
What do I do if i have many endpoints that need to determine the identity of the calling user? Can I mark them with some annotations, use some sort of security provider / authenticator (where I can add my own logic for validating - eg check to see if the token isn't older than 5 days, etc).
Do they need the identity? Or do they just need to know that the user is allowed to access them? If the latter, the easiest method is to put a suitable #RolesAllowed annotation on the method, at which point (with suitable configuration; see the JEE5 security docs). If the former, you need to get the HttpServletRequest object for the current action and call its getUserPrincipal() method to get the user's identity (or null if they've not logged in yet). This SO question describes how to go about getting the request object; there are a few possible ways to do it but I recommend injection via a #Resource annotation.
What I wouldn't do is allow users to normally provide their own identity via a #QueryParam; that's just wildly open to abuse. You can allow them to ask about other users that way, but then you need to decide whether you are going to tell them anything or not based on whether the current user is permitted to know anything about the other user. That's the sort of complex security problem that comes up in a real app, and is a good point for needing the current verified user identity.