flask-jwt-extended - Catch raise RevokedTokenError('Token has been revoked') - jwt

I already tried reading the documents as well try out the changing default behaviors https://flask-jwt-extended.readthedocs.io/en/latest/changing_default_behavior.html to handle the error (the link shows how to handle expired token) and search around in google everything in every keyword combination i could do but seems no one has example about this.
I tried using #jwt.revoked_token_loader to handle the RevokedTokenError but it seems it doesn't work as I applied it like this
#jwt.revoked_token_loader
def revoked_token_response(revoked_token):
jwtkn = revoked_token['jti']
return jsonsify({
'msg': 'token {} already been revoked!'.format(jwtkn)
)}, 401
actually, i don't know exactly how does the example on the link to handle expired tokens had parameter of 'expired_token', is that self-declaration like what I did above on the 'revoked_token'?? as far as I know, 'jti' is like a default value in the flask-jwt-extended package as I see error whenever I don't use this (in my db, it is different but there is no problem at all.
I tried following this tutorial and it works out fine on my side (as well his original code source) but I see that this one doesn't have a catch exception also on Revoke Tokens https://codeburst.io/jwt-authorization-in-flask-c63c1acf4eeb
I use postman and if based on the tutorial link, here's how i get this
i do login
i use the access token generated to access protected routes ('/secrets')
i do logout
i use again the access token generated to access protected routes
after the last one, i get this error on my server side (ide):
....flask_jwt_extended\utils.py", line 216, in verify_token_not_blacklisted
raise RevokedTokenError('Token has been revoked')
flask_jwt_extended.exceptions.RevokedTokenError: Token has been revoked
127.0.0.1 -- [02/Jul/2019 22:25:26] "GET /secrets HTTP/1.1" 500 -
in postman, this is what I get:
{
'message': 'Internal Server Error'
}
my target is to send out a custom json response instead of 'Internal Server Error'
edit:
I am no wiz on programming or such, a beginner that wanted to practice out python about secured web development. I don't yet quite understand still how decorator works out in terms of application, etc. so i don't know if others tweaks out the flask-jwt-extended package to work such things out.

Getting back a 500 error normally occurs because of a bug in other flask extensions and how that interact with native flask errorhandlers. You can find a bunch of discussions about it here (https://github.com/vimalloc/flask-jwt-extended/issues/86), but the tl;dr version is you might need to set app.config['PROPAGATE_EXCEPTIONS'] = True if using something like Flask-Restul, or use a hack like this if using flask-restplus:
jwt = JWTManager(app)
api = Api()
jwt._set_error_handler_callbacks(api)
If those don't help you, please take a look through that linked github issue, and if nothing in there helps make a reply in that issue detailing your setup.
Cheers.

Related

Facebook auth serverside calls back 2 times with the same code

On our server-side authentication with Facebook we get a random and weird issue. Facebook calls the call back URL two times with the same code. This is only happening for some users and not on every login.
This is the flow we have implemented on our side: https://developers.facebook.com/…/manually-build-a-login-fl… . We have been using it since the beginning of 2013 and we haven't noticed any issues so far.
And this is the error we get when we are exchanging the code for an access token the second time.
{"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100,"fbtrace_id":"traceID"}}
We tried to log this issue as a bug on https://developers.facebook.com/bugs but unfortunately it doesn't work.
It keeps showing unexpected error. Not to mention that i was unable to find the correct bug category.
Any idea on how we can fix this?
Thanks!
Could it be that users are clicking twice to process auth service? Try disabling the button before calling Facebook auth service
What language are you using?
I just had this problem in Ruby using Devise for Rails. I had created an omniauth.rb initializer file, and added a config line item in the devise.rb initializer file.
If you did this too, you can remove the omniauth.rb initializer file and you should be good to go!

Facebook Login using scribe

I'm using scribe to get user id, however I get this error:
OAuthConnectionException: There was a problem while creating a connection to the remote service.
I follow this example enhanced with javax filters (to get the parameter code correctly)
https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/FacebookExample.java
I also tried doing things manually and i got the access token which looks somehow like this ( i changed it a bit ) CAAHZCFE7YllgBAAZAenKbvZBrMZAZBkDGgydU2vAekwsM1V0StpZAgHXukEYWIDSpc5ZCXc4LB6suFeaPagcpj2ju6ayvAgrxYttvCQg9i7ZAdcF2ZCvhMNqTddsDUkNq1c1cX47U9KwutS5t6xpbV0cRabaVpgZCZAo4ZCTEtgckFmMajsb3zYWTH9LEfKj3CgcJ39lD2x1yRoXyAds0lKARmHZC
and while asking for user id like this:
https://graph.facebook.com/me?access_token=CAAHZCFE7YllgBAAZAenKbvZBrMZAZBkDGgydU2vAekwsM1V0StpZAgHXukEYWIDSpc5ZCXc4LB6suFeaPagcsj2ju6aYvYgrxYttvCQg9i7ZAdcF2ZCvhMNqTddsDUkNq1c1cX47U9KwutS5t6xpbV0cRabaVpgZCZAo4ZCTEtgckFmMajsb3zYWTH7LEfKj3CycJ39lD2x1yRoXyAds0lWLRmHZC%20,%20458856e03b909f426ec5d3791f0af466?fields=id,name
I get Malformed access token.
Do you have any suggestions regarding what I am doing wrong?
The URLs are the same, dunno what my mistake is :/

Play Framework: Don't change URL after form validation failed

In a plain Play application I have the following scenario.
A route file which looks like this:
GET /accounts/add controllers.Accounts.add()
POST /accounts controllers.Accounts.create()
The first route results in a view where I can add a new account. The form to submit the new account looks something like this:
#helper.form(action = routes.Accounts.create()) {...}
Now the controller binds the input to the form and checks for any validation errors:
public static Result create() {
Form<Account> form = Form.form(Account.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(views.html.account.add.render(form));
}
...
}
Now the thing is, the client will see the same view with some additional error messages. However, meanwhile the URL has changed from http://example.com/accounts/add to http://example.com/accounts.
If the client now reloads the browser this calls GET http://example.com/accounts (which isn't even mapped in this scenario - thus getting a 404 - Not Found).
Maybe it's just me but I find this kind of annoying and browsing some GitHub projects I couldn't find a good solution for this case.
Of cause things would be much simpler if the second route is rewritten to:
POST /accounts/add controllers.Accounts.create()
... in which case everything works fine. But from a REST point of view this doesn't feel good either. The same applies to update scenarios (having GET /accounts/:id/update vs. PUT /accounts/:id).
Is there a guide on how to handle this? Am I getting something wrong or is this no problem at all (from a pragmatic point of view)?
It's not possible to leave the previous URL because a request for a new address has already been made. A controller only provides response for a requested resource. To go to the previous URL you could only make a redirect in case of validation failure but you would lost errors that way so this is not a solution.
I suggest mapping both actions with the same URL. This way you would solve problem with the browser reload.
If you create a REST service for http clients that aren't browsers you will probably want to serve different response than a simple http page. The separation of actions for particular clients could be a good solution for keeping REST API clean and a browser user happy.

redirect_uri and how to host callback.html on SoundCloud?

I am trying to access Soundcloud from a local HTML page on my laptop. I am stuck at the part of hosting "callback.html" as a redirect_uri. The script I am trying to run is the basic Authenication JavaScript from the Soundcloud documentation page:
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
// initialize client with app credentials
SC.initialize({
client_id: 'my_client_id',
redirect_uri: 'http://127.0.0.1/Users/Maria/Documents/SoundcloudClient/callback.html'
});
// initiate auth popup
SC.connect(function() {
SC.get('/me', function(me) {
alert('Hello, ' + me.username);
});
});
</script>
This script gets me to the connect pop-up when I launch the page in Chrome and Firefox.
But, once I have logged in as a Soundcloud user, I get the following error:
Oops! Google Chrome could not connect to 127.0.0.1
If I change my redirect_uri to localhost I get the same error.
If I try:
files:///C:/Users/Maria/Documents/SoundcloudThinClient/callback.html
I get a similar error.
I also tried:
ocalhost:3000
and:
localhost:8080
even though I'm not sure what would be listening on those ports.
So, basically, I'm asking what path do I put for callback.html in order for this to work?
I confess I don't know how the redirct_uri actually functions. I looked at the Oauth pages for it, but I don't understand them. I am beginning to think that I can't simply create an HTML page, paste the JavaScript, create a callback.html file and have this work, even though the SC documentation seems to say that this is possible. If so, what steps am I missing?
I am beginning to attempt this. I believe you have to go to the developer site and sign up as having an app. The redirect uri is asked for and the form gives you an API key you can use in your app.
I'm using drupal so, perhaps adding the oath module and using Php to add the api key might work well.
I had the same problem and I think I solved it.
Morning-after-edit: I posted this dead-tired after working towards a solution through the night. Now, the day after, I realize that you were speaking about the general problem, whereof I face a very particular instance. The following only applies directly to registering soundcloudlabs' soundcloud-group-recorder: https://github.com/soundcloudlabs/soundcloud-group-recorder. There is probably a more general principle lurking behind there, though:
First: yes, you do have to register the app as your own at Soundcloud. At least I presumed so. And doing that, you must register correctly where on your server you will place the callback.html file. Take the ClientID assigned to your app and use that in the API intialize procedure.
Now, I'm a novice and know very little coding. But I started looking around in the main file, application.js.
At the top of the file there are two instances of client_id and redirect_uri each. I'm not sure if that serves a purpose or if one is technically superfluous. Through trial and error I found out that replacing the second instance of each with my own data worked.
Then there is groupId and groupUrl, both of which should contain your info, within quotation marks.
After a lot of trial and error, still having trouble getting the thing to run, I looked around and saw that, whereas early in the file, client_id was hooked within SC.initialize, redirect_uri was not. Under the line:
client_id: CLIENT_ID
I added:
redirect_uri: REDIRECT_URI
– with a customary comma in between. And that's it. It runs.

Always get "Error validating verification code." when requesting access_token

Well, I have done all my best to try to solve this problem, but, still, it's too annoying.
I decided to use OAuth with server-side authentication. So, I have followed Facebook documentation, and I have done the following step.
Create a link which redirect people to log in Facebook by https://www.facebook.com/dialog/oauth?client_id={APP_ID}&redirect_uri=http://abc.com/nextStep.php
In nextStep.php, redirect people to https://graph.facebook.com/oauth/access_token?code={CODE GENERATED BY FACEBOOK}&client_id={APP_ID}&redirect_uri=http://abc.com/thirdStep.php&client_secret={APP_SECRET}
The problem exists when proceeding to step 2. The page shows that:
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I have googled for lots of time. Some people suggests to add a trailing slash in the redirect_uri, but it doesn't work. What should I do? And how can I get the user information after getting the access_token? Thanks for your help.
Two things:
First, I’d say you’re missing the state parameter in your first URL … you have to make up a value that the docs describe as SOME_ARBITRARY_BUT_UNIQUE_STRING – some unique id/hash/whatever, that no one from the outside would be able to guess. (Yes, that parameter is optional – but you should use it anyway, because as the docs say it helps prevent CSRF and is therefore an important security measure. If you don’t know what CSRF means, please look it up.)
And second, in your step two, you should not redirect the user’s client to that address, but make a server side call to that endpoint instead. You are putting your app secret into this URL (that’s not the mistake, you have to) – so it would be easy for the user to get it if you called that URL in his browser …!
I’d suggest you start with https://developers.facebook.com/docs/authentication/server-side/ again, reading it carefully from the top – you can hardly go wrong if you really follow the instructions given there one-by-one …