Flask login mechanisim to authenticate per token my calls - authentication

Hi I was looking at flask-login at handles the session login nicely, this work good for templating and views where I have access to the session.
Nevertheless I have been trying to know if there is a way I can send a user_token to authorized a call. I looked at the documentstion and is very vague regarding this. It said that I should
Implement get_auth_token in my User object.
Decorte a #user_loader function that can load the user token base.
I have though seen the following (please correct me If I am wrong)
Cookie base to store the auth token is there a way I can decide to send the token as part of the parameters, body or in the headers insteado having to get it from the cookie.
I am not quite sure how to authenticate a call with auth token.

I got a Way better approach that fits better my needs. Basically I extends LoginManager pretty easy and straighfoward if you take a look at the source of flask-plugin you come to realize that there is a call that is made #before_request there is a method called reload_user, this is the what I end up doing
class CustomLoginManager(LoginManager):
def reload_user(self):
if request.headers.has_key('Authorization'):
ctx = _request_ctx_stack.top
ctx.user = User.get(token=request.headers['Authorization'])
return
super(CustomLoginManager,self).reload_user()
If in my header I pass an authorization key then I will try to load using this key instead of session based approach, of course I am going to need to add more security layer to this approach proably by signing the key but overall this was what I needed.
Thanks all.
BTW you can override a bunch of others method and I highly recomend to take a look at the plugin source, so you can understand more deeply what it does 644 lines of codes worth reading
https://github.com/maxcountryman/flask-login/blob/master/flask_login.py

It seems like you're wanting something like OAuth instead of using Flask-Login. In case you don't know (quoted from Wikipedia), OAuth is a protocol that utilizes tokens in order to access resources on behalf of a resource owner. Think giving a user the ability to give out a valet key to certain portions of your site. Many sites, such as Google, Facebook, and Twitter use OAuth for authenticating third party clients in order to access certain user resources.
Right now, there's a split between the less flexible and less complex OAuth 1.0a and the more flexible but more complex OAuth 2.0. Many libraries exist for OAuth 1.0a in Python, but fewer for OAuth 2.0. However, there is a selection of those for OAuth 2.0 if stability isn't a top concern right now.
For the client, Flask-OAuth is available if you're going with OAuth 1.0a, and it is maintained by Armin, the Flask creator itself, so you can feel assured that it won't die. For the provider, there's an extension called Flask-OAuthProvider with OAuth 1.0a support. If you don't mind integrating it yourself and want 2.0 support, pyoauth2 provides you with both a client and a provider, though it looks less maintained.
Hopefully this helps you with exploring one possible avenue to utilize auth tokens, albeit without using Flask-Login. In my opinion, one shouldn't re-implement a protocol unless they understand it, so I recommend reading up about OAuth even if you decide not to use it. Many great articles exist on it, such as this article from Google and this one, too.

Just as an update, Flask-Login now has a 'header_loader' function, which can be used in conjunction with the standard 'user_loader'. Taken directly from the docs:
#login_manager.header_loader
def load_user_from_header(header_val):
if header_val.startswith('Basic '):
header_val = header_val.replace('Basic ', '', 1)
try:
header_val = base64.b64decode(header_val)
except TypeError:
pass
return User.query.filter_by(api_key=header_val).first()
Here's the link to the section in the Flask-Login docs

Related

How to get OAuth 2.0 right for consuming external APIs in my Custom API .net core

I want to create a custom API that behind the scenes, call number of other APIs which use OAuth 2.0 for authentication. I want to manage this internally so that my custom endpoint somewhat abstract this.
Or to begin with I want to do what app like buffer (https://buffer.com) do - where you connect to different social services and than post your status.
How can I achieve this in .NetCore ?? I don't want to login with these (a lot of samples are catering this scenario), user login is different than this. I just want to establish these connections (like API Connections if you look at Azure API Management) and then perform some operations against those endpoints.
I hope i convey my point. please let me know if this isn't clear.
Thanks
Sanjay
OAuth2 systems are all based on the same workflow.
here's an authorization url, you pass some ids in an authorization header, if everything is correct you get a token, you then use the token to do whatever you are allowed to do. What changes are the credentials you use for authentication and the urls you hit for the various parts of this workflow.
You could write your own OAuth2 library which deals with all this, that's pretty much what I did and simply changed the details for every specific system I had to interact with.
This being said you can always use one of the existing implementations to connect to the various systems you care about, they all have an API you could use, all you have to do is make sure you follow the OAuth2 flow correctly.

Symfony 2 API authentication method

I have a JSON REST API written in Symfony 2.7, and I want to authenticate & authorize users. This is my first time doing this, so I have some doubts/questions.
For that, I thought several methods:
User & password, and then save a session in the back end
Same as 1), but add an "apiToken" (randomly generate when user register) and then sending back & forth the apiToken in every single request to check user identity.
Use OAuth (which I'm currently reading about it).
I read that using OAuth for a simple API is like an "overkill", but on the safe side it sticks to standards and also allows me to use it when using my API with mobile devices and different platforms.
Also, I don't know too much about security flaws of using method 1) or 2).
I know this is maybe based on opinions, but I don't know any other site to post this question, as Symfony official mailing was shut down and migrate here it seems.
As you seems to know, your question is too opinion based.
If I can give you some advices (too long for a 600chars comment),
OAuth is powerful, but so much free.
I mean that you can easily implement it sort as everything works well while having a set of potential security issues without being aware of their existence.
Libraries and bundles providing OAuth are hard to maintain because of the new security issues regularly found.
On the other hand, if you need the benefits of OAuth (be a client and/or a server, compatible with the most part of social networks), go learn OAuth and do your experience with it.
Otherwise, use a simple credentials/request token two-step authentication.
See the JWT Authentication tutorial by KnpLabs,
Symfony Guard Authentication by Ryan Weaver,
and the great LexikJWTAuthenticationBundle, easy to implement and to use.

Simple RESTful API authentication

I'm building a single-page web application, fully based on RESTful API. I've seen several topics in that matter, but some things remain unclear for me.
I will need users to log in. Here are some of my ideas:
I can send e-mail and password to API and use basic auth. I'm not sure where should I keep password, should it be encrypted and if so: how?
Can I use built-in session system instead? Is it wrong to use cookies directly in the RESTful API? Why is it so popular to send credentials/keys to API itself instead of using cookies?
I thought about having one API key per user, return it in login action and keep it in localStorage. I guess it's not the greatest idea to have just one key per user?
Then, I came up with idea to have separate keys table and add random keys each time somebody logs in. On logout, the key would go away and no longer be valid. This is more secure than previous idea.
How is it solved in simple projects? I'd like to make it simple but not ridiculously inserure.
Please help.
The commonly approach is to use the header Authorization in REST. The state of the application must be on the client side with REST and shouldn'a be tied to a particularly client kind (browser with cookies)
I think that this link could be helpful:
Implementing authentication with tokens for RESTful applications : https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/
There is also à great question to à similar question here : https://softwareengineering.stackexchange.com/questions/141019/should-cookies-be-used-in-a-restful-api
Hope it helps,
Thierry

API Authentication using OAuth help needed

Background: I am trying to create an SMS API service. The developers have a Dev ID, and an API secret key assigned to their developer account. The developers will be creating apps which will issue calls to my API. But the application issuing the call must be verified first.
Issue: The main issue i have is with authentication. I read up on OAuth and pretty much uderstood it. I read through this presentation (Slide 71-82). All OAuth articles talk about the OAuth 'dance' or the 'love triangle'. My problem seems to be, that i dont see a proper triangle in my case. Or, a better way to put it would be, the triangle doesn't seem to be complete.
What i mean by that is, in the case of lets say, LinkedIn, trying to make some app which helps users associate their LinkedIn acc with twitter, OAuth makes complete sense. Because LinkedIn needs to get resources from twitter ON THE USERS BEHALF (Cuz the user HAS A TWITTER ACCOUNT). In my case, only the consumer has a developer account registered with my service. The end-user doesn't have any credentials for the consumer to ask on behalf of. So how can i implement Oauth? So what will the consumer ask the provider? Will it only state that "watch out, here i come?". Cuz that seems pretty pointless unless its asking for a request token in exchange for an access token. But in this case since the end user doesnt even have an account, the steps seem useless.
So, i cant figure out how to go about this authentication issue. Ive tried thinking about using php sessions so it can help me associate a token with the particular client who is using the API. But the REST/OAUTH purists seem to disagree on the usage of sessions in authentication. They claim that OAuth is a standard which has proven itself and that is what I should use instead of coming up with my own obscure schemes.
From your description it seem that you're in a two party scenario only (developers write code which accesses your API on their own behalf, not on behalf of an end-user), so that means indeed that doing the full 3-legged oAuth scenario isn't needed.
You could use pretty much any authentication scheme and that would work (API Keys, other oAuth grant types [see below] or even ID/Secret combinations. In the oAuth world:
Look at the other oAuth 2.0 Grant types: especially resource owner PW grants - https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-26#section-4.3. It's slightly better than username-password because the PW isn't passed across the channel all the time (it passes once though) and it assumes the developer writing the code is the owner of the credentials.
Look at oAuth v1.0: this different in various ways to v2.0 but one feature it does have which some people like is the way tokens are used - which is rather than being passed across the wire they are used to generate a hash in the client and then the hash is verified on the server side. It's more expensive and complex than checking a key but it's less prone to attack.
In the non-oAuth world, if it's primarily a server resource used by developers directly, an ID/Secret or API-Key pattern is probably more than sufficient and it's much easier to implement for your developers.
Re: oAuth - if you're doing any type of user auth then definitely stick with the standard - the stuff is complex and having libraries out there really helps. If it's developer-api you likely don't need to go that far.
If you want the API to be secure in an ideal world anything which requires the security token to pass across the gaps should be secured using SSL, especially if that client code could be running on a mobile device or laptop which might communicate over wireless. If this isn't the case, someone could jump in an copy a token from one of the devs.
The only one of the protocols above that avoids this is the oAuth 1.0 variation since the secret never leaves the client but is used to hash instead. But it's complex. Last one to look at is the Amazon AWS pattern which does hashing similar to oAuth 1.0 http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html and people emulate quite a bit.

Do I need to secure my API?

I'm working on an API service for my website. I have read a lot on this topic, though can't decide which the best solution would be for me.
My API is simple. Each user gets an API key for each app that connects to my site.
There are only 2 different calls atm:
send_data
get_data
The get_data is quiet harmless, with send_data you can end new entries to your mini app. Possible security problems could occur there, though calls are limited. None of the data is useful if it would fall in the wrong hands. Server side I am protected for sql injection etc.
The calls are something like this:
http://example.com/api/?call=send_data&data=DATAXYZ&api_key=KEY
The pro:
It's super easy to use
The con:
It's not secure
I read a lot of similar questions here and elsewhere and OAuth pops up as a possible answer on almost all of them. I know OAuth, and i think it's a lot of overhead for something I want to be easy to use for my users.
As explained in this article It's not always needed to use authorization:
http://blog.apigee.com/detail/do_you_need_api_keys_api_identity_vs._authorization/
Is this all true for my case too though or would you still recommend authentication with or without OAuth?
Don't send the API key as a GET parameter: it would be logged at the very least in the browser's history (and probably also in the proxy, if there's one), which isn't very secure. POST it instead.
I don't think it would be unsecure, in fact the widely used Basic Access Authentication sends the username and the password as plain text (base64 encoded), and in fact when using a form to log into any web service you are sending the password as plain text too. Of course this works on the assumption that the communications between the client and server are secure, so you probably want to use HTTPS.
I'm personally using similar API authentication methods in multiple commercial projects.
So far I've never had an issue with security but I use a slightly different approach.
What I do different:
a) API calls use a user-id/login plus an API key.
b) the API key is a salted md5 hash of the users password (you can add the userid and something else as salt)
That means people are less likely trying to "guess" an API key, you can also more easily see who is using your API in your logs (without looking up the API key).
And users can change their API key by changing their password, so if they think the API credentials might have been leaked then they can just change it.
Regarding GET/POST : If your users do not use the API themself (for example by including it in own tools/scripts/code) then I'd use POST as serans suggested.
But POST has several drawbacks, it's not as "easy" to use. It just requires a bit more work to be implemented.
So I'd offer GET as well as POST and just add a note about possible security issues.