caffeinehit / django-oauth2-provider Goto Github PK
View Code? Open in Web Editor NEWProvide OAuth2 access to your app
Home Page: http://www.caffeinehit.com/work/code/django-oauth2-provider/
License: MIT License
Provide OAuth2 access to your app
Home Page: http://www.caffeinehit.com/work/code/django-oauth2-provider/
License: MIT License
I can login using different user/pass credentials but reusing the client_id / client_secret of another user. This is a problem for misbehaving apps accessing the server.
Hi!,
I would like to authenticate an user whether using session or using oauth token, how to perform OR condition in middleware ?
Im using django-oauth2-provider to build a authorization server. When i try to get access_token by using this command:
curl -d "client_id=513204402d4b4f4d62e2&grant_type=authorization_code&response_type=code" http://127.0.0.1:8000/oauth2/access_token
i got an error: invalid_client
I have been created my client with client_type is Confidential How can i fix it?
The library has been very useful, but shouldn't it also include signature methods? Methods like RSA-SHA1 or HMAC-SHA1.
Although I couldnt find signature methods being defined in Oauth2 standards here : http://tools.ietf.org/html/rfc6749
Yet in an earlier versions, there is mention of signature methods : http://tools.ietf.org/html/rfc5849#section-3.4.3
First of all. Thank you! This app would be very helpful if I could manage to make it work.
I try to add OAuth2 authentication scheme to Django rest framework. I'm following the documentation: http://www.django-rest-framework.org/api-guide/authentication It states that 'provider.oauth2' shall be added to INSTALLED_APPS. However, if I do that I keep getting the same error:
Traceback (most recent call last):
File "/Users/user/s/lib/python3.4/site-packages/django/apps/config.py", line 114, in create
cls = getattr(mod, cls_name)
AttributeError: 'module' object has no attribute 'oauth2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/PycharmProjects/s/manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/Users/user/s/lib/python3.4/site-packages/django/core/management/init.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/user/s/lib/python3.4/site-packages/django/core/management/init.py", line 354, in execute
django.setup()
File "/Users/user/s/lib/python3.4/site-packages/django/init.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/user/s/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Users/user/s/lib/python3.4/site-packages/django/apps/config.py", line 120, in create
"cannot import name '%s' from '%s'" % (cls_name, mod_path))
ImportError: cannot import name 'oauth2' from 'provider'
Process finished with exit code 1
Hi,
It seems that pypi version if half a year old, some cool staff was merged duiring this time (like optional secret for public clients). Why haven't you bothered to upload fresher version into pypi?
I'm using Django 1.7c1
Not considering the minetype issue for a while.
When I ask for a token like so:
$ curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
I get back:
{ "access_token": "0268b3a410bbbffdf2fe41a3f31fcf8a7b810ffd", "token_type": "Bearer", "expires_in": 2591999, "scope": "read" }
Now... where is the "refresh_token"
?
Is there an hidden setting that I'm not considering or is it a bug?
Thanks!
I want to generate an access token for the client coming after getting access token from facebook. I have to check the facebook access token and respond with my internally generated oauth access token. Is there a way to generate an access token without providing username and password information.
Hello there,
I'm trying to get this library to work. The installation works fine but when I run the code on a Django 1.6 installation, I get the following error after authorizing my app:
<Client: http://localhost:8001/callback> is not JSON serializable
Stacktrace:
Environment:
Request Method: POST
Request URL: http://localhost:8000/oauth2/authorize/confirm
Django Version: 1.6
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'provider',
'provider.oauth2',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/tnaessens/Documents/Projects/Python/oauth2-provider/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
201. response = middleware_method(request, response)
File "/home/tnaessens/Documents/Projects/Python/oauth2-provider/env/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py" in process_response
38. request.session.save()
File "/home/tnaessens/Documents/Projects/Python/oauth2-provider/env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
57. session_data=self.encode(self._get_session(no_load=must_create)),
File "/home/tnaessens/Documents/Projects/Python/oauth2-provider/env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in encode
87. serialized = self.serializer().dumps(session_dict)
File "/home/tnaessens/Documents/Projects/Python/oauth2-provider/env/local/lib/python2.7/site-packages/django/core/signing.py" in dumps
88. return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
250. sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
207. chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
270. return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /oauth2/authorize/confirm
Exception Value: <Client: http://localhost:8001/callback> is not JSON serializable
By googling, I found this similar bug in django-allauth: pennersr/django-allauth#386. This was caused by the change from PickleSerializer to JSONSerializer from Django 1.5 to 1.6 as described here.
Obviously since march 18. Give ownership to another before the project itself dies.
Hello,
Django 1.8 migrations are being broken for me. I use django 1.8.4 and django-oauth2-provider 1.0.1 but i get the error bellow. I overwrote the custom user mode.
I think this issue is related to these:
jazzband/django-oauth-toolkit#204
https://code.djangoproject.com/ticket/24524
This project is not maintained anymore but changing now in production would be a lot of work that i am not as happy to do. Did anybody found a solution to this? I found a hack to it by commenting the installed apps, running the migrations and then un-commenting them again:
# 'provider',
# 'provider.oauth2',
That is not that nice though and breaks my test running also.
Traceback (most recent call last):
File "manage.py", line 7, in
execute_from_command_line(sys.argv)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/init.py", line 338, in execute_from_command_line
utility.execute()
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/init.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(_args, *_cmd_options)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
output = self.handle(_args, *_options)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 318, in sync_apps
cursor.execute(statement)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in exit
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/vlad/work/gekkolab/ve/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "accounts_customuser" does not exist
Best,
Vlad
As described here:
http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.2
And (somewhat more accessibly), here:
http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified#browser-based-apps
It seems to me that it would be sensible to disable 2-legged authentication for public clients. I say this because public clients (by definition?) should not have access to the client secret, which is required for 2-legged OAuth2.
Therefore, I would like to disable 2-legged auth for public clients, as I don't want to encourage anyone to start distributing their client secrets out of ignorance.
I'd be happy to create a pull request, but can someone chime in on the sanity of this idea?
The problem is that the code expects the client.redirect_url
variable to exist which it doesn't in all cases: https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/views.py#L297
Traceback (most recent call last):
File "readbox/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "readbox/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, *args, **kwargs)
File "readbox/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "readbox/lib/python2.7/site-packages/provider/views.py", line 39, in dispatch
response = super(OAuthView, self).dispatch(request, *args, **kwargs)
File "readbox/lib/python2.7/site-packages/django/views/generic/base.py", line 86, in dispatch
return handler(request, *args, **kwargs)
File "readbox/lib/python2.7/site-packages/provider/views.py", line 297, in get
redirect_uri = data.get('redirect_uri', None) or client.redirect_uri
AttributeError: 'NoneType' object has no attribute 'redirect_uri'
Could anyone advise on changing the expiry date for a token?
I would like to set a token that only valid for 2 hours. Every time I generate a token via access_token, I will get a token with "expires_in:2591999".
Great thanks for help!
When OAUTH_SINGLE_ACCESS_TOKEN
is set to True
then instead of always creating a new token we check whether one with the same client user and scope already exists and we return that instead:
def get_access_token(self, request, user, scope, client):
try:
# Attempt to fetch an existing access token.
at = AccessToken.objects.get(user=user, client=client, scope=scope)
except AccessToken.DoesNotExist:
# None found... make a new one!
at = self.create_access_token(request, user, scope, client)
self.create_refresh_token(request, user, scope, at, client)
return at
Note that this does not check for token expiry when fetching the access token.
If OAUTH_DELETE_EXPIRED
is set to False
(default) then if we hit the access_token endpoint with grant_type=refresh_token and pass the refresh token from a previous access token then the refresh process will just create a second access token:
def refresh_token(self, request, data, client):
"""
Handle ``grant_type=refresh_token`` requests as defined in :rfc:`6`.
"""
rt = self.get_refresh_token_grant(request, data, client)
# this must be called first in case we need to purge expired tokens
self.invalidate_refresh_token(rt)
self.invalidate_access_token(rt.access_token)
at = self.create_access_token(request, rt.user, rt.access_token.scope,
client)
rt = self.create_refresh_token(request, at.user, at.scope, at, client)
return self.access_token_response(at)
The invalidate_access_token
function will just set the expiry date and we end up with 2 access tokens in our db with the same client, user and scope.
This results in get_access_token
above bombing out at
AccessToken.objects.get(user=user, client=client, scope=scope)
with a multiple objects returned error.
I think that OAUTH_SINGLE_ACCESS_TOKEN
should either automatically enable OAUTH_DELETE_EXPIRED
or at a minimum I think the old access token should be deleted on refresh.
I'm happy to reopen this as a pull request if the above solution sounds good.
Hi,
First, thanks for making this.
Having one issue: does the access_token endpoint not accept JSON? Only form-encoded?
Thanks,
Aaron
HI,
how can I get the "access token" using the authorization_code as the grant_type? I read that it is not reccommended to get the access code using username and password.
Regards,
Fabio
When I try to run setup.py install, or do it with pip I get the following error:
File "C:\Python27\lib\distutils\filelist.py", line 118, in process_template_li
ne
action, patterns, dir, dir_pattern = self._parse_template_line(line)
File "C:\Python27\lib\distutils\filelist.py", line 97, in _parse_template_line
dir = convert_path(words[1])
File "C:\Python27\lib\distutils\util.py", line 202, in convert_path
raise ValueError, "path '%s' cannot end with '/'" % pathname
ValueError: path 'provider/' cannot end with '/'
This library has been great so far but I have one issue.
I've pored over the docs and I'm unable to find any mention of the ability to throttle the number of login requests per second / locking out users who attempt too many bad requests in a given time period.
I'm currently using django-axes but it seems that its middleware doesn't extend to the provider.
The spec still seems to be changing regularly (latest update was published June 19th). I'm curious which version you're targeting?
Hi,
I will intend to package of debian, so I will ask license of this software.
Which license, BSD License, or The MIT Licsense, is correct?
"License :: OSI Approved :: BSD License" is written In setup.py,
but the content of LICENSE file is The MIT License.
Best regards,
I noticed that when using grant_type=password
and incorrect credentials are provided through the username
and password
fields, the server returns the following:
{
"error": "invalid_grant"
}
Is this an expected result?
Thanks
Thank you very much for the project. Just curious if work on this project has been discontinued. I see that there has not been a commit on master in over 16 months. This might indicate that the project maintainers have moved on. If so, what are the maintainers using? I've seen in the comments of issues and PRs references to django-oauth-toolkit as a viable solution. It appears to be more actively maintained with more contributors and greater throughput on issues.
Please advise as to the state of this project. If the project is not actively maintained, it might be helpful to put that in the README.md.
Thanks again for the OSS.
it's common for mobile applications to use non-standard schemes that don't pass URLField's standard validations. iOS uses app specific schemes myapp://... and modern Windows uses ms-app://...
oauth2 provider works fine with these redirect_uri's set, but i have to go directly to the database to set them (going around the validations.)
really new Django allows a list of schemes to be passed to URLField/validators, but that won't really work here since iOS's schemes are app-specific. the only real solution i can think of is a more lenient URLField/validator for redirect_uri that doesn't check the scheme.
it could (perahps should) be an optional thing enabled with a setting, but i currently have run across several cases where i've had needed the ability to use a non-standard scheme.
It appears that OAuth2 backends are using database lookups to validate access tokens. While relational databases are great for performant lookups, they're not so great for comparing cryptographic secrets without leaking timing information. To wit:
A Python function that addresses this has already been written in the EFF's OpenWireless project
the link in the description of the project (http://www.caffeinehit.com/work/code/django-oauth2-provider/) now land on the homepage of caffeine hit. Maybe condiser making it point to the django-oauth readthedocs section ?
When response_type = token is provided to the authorize endpoint, the resulting redirect after authorization confirmation is a "code" (just like response_type=code). It would appear the implicit grant flow as described in section 4.2.1 of RFC 6749 is not implemented.
Hi,
Firstly, thanks for taking the time to keep this project up ๐ . You make my life easier.
I have a django-rest-framework Framework project, let's call it MyApp, that uses django-oauth2-provider for authentication.
Goal: To register and login a user for MyApp using his/her Facebook or Twitter credentials.
The client successfully gets the Facebook or Twitter authorization code, auth_code
. The client makes a POST to https://myapp.com/api/oauth2/access_token/
with:
grant_type=authorization_code
client_id=xxx
client_secret=xxx
code=auth_code
The response is always a 400 with "invalid_grant"
. I understand why: there is no provider.oauth2.models.Grant
entry with the matching provider.oauth2.models.Client
and auth_code
. In fact, there are no Grant
entries, period.
Should Grant
entries be created/invalidated by me somewhere? It seems like this should happen automagically.
Thanks,
Aaron
I was just able to save 2 clients with the same Client.client_id
. (and with the same secret for that matter). At least for the client_id
field there should be only 1.
I have a custom user model UserAccount
with db_table = 'accounts_user_account'
. I was getting database errors when attempting to save and realized the foreign key restraints were referencing accounts_useraccount
instead of the above custom set table name. Any chance django-oauth2-provider could derive this table name automatically?
include LICENSE
include README.rst
recursive-include provider/templates *.html
recursive-include provider/templates *.txt
recursive-include provider/ *json
File "x:\Python27\lib\distutils\util.py", line 201, in convert_path
raise ValueError, "path '%s' cannot end with '/'" % pathname
issue occurs when os.sep != '/'
solution is remove tailing /(provider/ => provider) at last line of MANIFEST.in
I'd suggest adding human-readable scope descriptions in configuration, instead of keeping them template-only hack.
I.e. I mean something like this:
OAUTH_SCOPES = (
(READ, "read", _(u"Read your data")),
(READ_WRITE, "write", _(u"Write your data")),
)
Or, maybe, separating permissions from scopes:
OAUTH_PERMISSIONS = {
READ: _(u"Read your data"),
WRITE: _(u"Write your data"),
}
assert all((is_power_of_two(k) for k in OAUTH_PERMISSIONS.keys()))
OAUTH_SCOPES = (
(READ, "read"),
(READ_WRITE, "write"),
)
Then, instead of {% if permission == "read" %}...{% else %}...{% endif %}
hack do something like:
{% for permission in oauth_data.scope|scopes_permissions %}
<li>{{ permission }}</li>
{% endfor %}
However, I'm unsure on how this should be actually done.
This refers to issue #51
Client
serialization introduced in eculver/django-oauth2-provider@8a97e5e2e63fb still fails when user
is NULL.
Here is my traceback:
Traceback (most recent call last):
File "/home/peter/work/lb/lectures/authviidea/tests.py", line 76, in testAuthorize
authorize='Authorize'
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/test/client.py", line 483, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/test/client.py", line 302, in post
return self.request(**r)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/test/client.py", line 444, in request
six.reraise(*exc_info)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/peter/work/lb/parts/django-oauth2-provider/provider/views.py", line 41, in dispatch
response = super(OAuthView, self).dispatch(request, *args, **kwargs)
File "/home/peter/tmp/buildout-cache/eggs/Django-1.6.1-py2.7.egg/django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "/home/peter/work/lb/parts/django-oauth2-provider/provider/views.py", line 285, in post
return self.handle(request, request.POST)
File "/home/peter/work/lb/lectures/authviidea/service/views.py", line 75, in handle
return super(AuthorizeView, self).handle(request, post_data)
File "/home/peter/work/lb/parts/django-oauth2-provider/provider/views.py", line 277, in handle
self.cache_data(request, client.serialize(), "client")
File "/home/peter/work/lb/parts/django-oauth2-provider/provider/oauth2/models.py", line 56, in serialize
return dict(user=serialize_instance(self.user),
File "/home/peter/work/lb/parts/django-oauth2-provider/provider/utils.py", line 79, in serialize_instance
for k, v in instance.__dict__.items()
AttributeError: 'NoneType' object has no attribute '__dict__'
Django 1.5 introduces Custom User model and deprecates get_profile().
I tried to reference the User model using the string (or settings.AUTH_USER_MODEL http://django.readthedocs.org/en/latest/topics/auth.html#referencing-the-user-model) but the unit tests fail with:
oauth2.client: 'user' has a relation with model django.contrib.auth.models.User, which has either not been installed or is abstract.
I also tried to reference it with models.get_model('django.contrib.auth.models', 'User') but it fails with:
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
It's like the library is loaded before django and I'm not sure how to fix it.
I'd be happy to provide a patch if you have any ideas
--Gilles
According to[0]:
Like browser-based apps, mobile apps also cannot maintain the confidentiality of their client secret. Because of this, mobile apps must also use an OAuth flow that does not require a client secret.
Based on this, shouldn't client_id be enough to get the access token to get access token? Since client_secret could be used for something not directly related to token.
[0] http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
I completed this locally (and i've never submitted any code changes so not quite sure how that works) most of it was around dict.iteritems -> dict.items, a few OExcept, e: needing to become OExcept as e:, reduce needing to be imported from functools and a bunch others. I will do a diff sometime of my final library and report the changes i made. (Unless someone wants to be kind and point me towards a how to contribute..)
I'm facing this issue every time I make POST request to /oauth2/access_token. This is my scenario:
I successfully integrated the provider and created a client from the admin console, without specifying any redirect uri because i'm working on localhost and I don't have any website yet. Now, if I try to get an access token at the specified url, I will get the token only if I make the request specifying username and password of an user which is admin. For any other user I will get "error: invalid grant". I tried every kind of solution but nothing seems to work.
I also noticed a strange thing: when I get the access token with the admin user, no grant and refresh token are created in the database...is this a normal behaviour?
I can't get this to work so how can I solve the problem?
When using Django 1.6 everything seems to work fine, if i request an access token i get it:
curl -X POST -d "client_id=0ca3f7c5ebbee468f266&client_secret=0dfc806ee685c0ffe7b47f7a0702edd77f8fa0ba&grant_type=password&username=manel&password=manel" http://vagrant-khan:8000/oauth2/access_token/
The problem is when i upgrade to Django 1.7 where i only get a 500 internal server error
but it still creates the access token in the database. Can you confirm this bug and provide a fix?
Django 1.4 introduces new timezone support. Looks to be a pretty straight forward update. I'll try and provide a patch soon if I can find some time otherwise I just wanted the issue documented.
https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/oauth2/models.py#L48
the unicode method returns a redirect_uri, which isn't very descriptive of a model Client.
maybe it should be something different?
Passing mimetype to HttpResponse is deprecated and removed in Django 1.7 as per django/django@8eadbc5
(https://github.com/caffeinehit/django-oauth2-provider/blob/master/provider/views.py#L491)
It breaks deletion on groups as django is looking for table auth_extenssionuser_groups.
from tox
I am getting this:
ERROR: py2.7-django.dev: commands failed ERROR: py2.7-django1.6: commands failed ERROR: py2.7-django1.5: commands failed ERROR: py2.7-django1.4: commands failed py2.6-django.dev: commands succeeded ERROR: py2.6-django1.6: commands failed ERROR: py2.6-django1.5: commands failed ERROR: py2.6-django1.4: commands failed
although python manage.py test
passes with
$ pip freeze Django==1.6.2 -e git+https://github.com/sesas/django-oauth2-provider.git@a7d7e0ffa434ef4d8cd0179bc6ae305fd7c5b099#egg=django_oauth2_provider-master tox==1.7.0
in which the -e installation is my fork of your most recent master
Hello!
Sometimes access_token api returns 500 error.
We use several databases in our project. And 500 error is due to the lag slave
Function password
is looks like:
def password(self, request, data, client):
"""
Handle ``grant_type=password`` requests as defined in :rfc:`4.3`.
"""
data = self.get_password_grant(request, data, client)
user = data.get('user')
scope = data.get('scope')
if constants.SINGLE_ACCESS_TOKEN:
at = self.get_access_token(request, user, scope, client)
else:
at = self.create_access_token(request, user, scope, client)
rt = self.create_refresh_token(request, user, scope, at, client)
return self.access_token_response(at)
refresh_token
is created in it (we don't user SINGLE_ACCESS_TOKEN option)
and it is retrieved from db in access_token_response
func.
In the case of slave lag, an exception DoesNotExists is raised.
I think, that passing refresh_token
into the access_token_response
can help. At the same time it saves a db request.
serialize_instance
function from provider.utils
uses default DjangoJSONEncoder
, which cannot serilaize model with custom fields. It would be better if one can specify encoder/decoder classnames in settings module.
Example:
...
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill, ResizeCanvas, Anchor
class User(BaseUser):
registered_at = models.DateTimeField(auto_now_add=True)
tags = models.ManyToManyField('core.Tag', through='core.TagLike')
avatar = models.ImageField(upload_to=upload_to('users'),
blank=True, null=True)
avatar_square = ImageSpecField(source='avatar', format='JPEG',
processors=[
ResizeToFill(300, 300),
ResizeCanvas(300, 300,
anchor=Anchor.CENTER)],
options={'quality': 75})
avatar_square_s = ImageSpecField(source='avatar', format='JPEG',
processors=[
ResizeToFill(100, 100),
ResizeCanvas(100, 100,
anchor=Anchor.CENTER)],
options={'quality': 90})
...
Trace
Environment:
Request Method: POST
Request URL: http://localhost:8000/oauth2/authorize/confirm
Django Version: 1.6.7
Python Version: 2.7.8
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'south',
'imagekit',
'django_babel',
'social.apps.django_app.default',
'pamphlet',
'pamphlet_images',
'pamphlet_tags',
'pamphlet_grid',
'pamphlet_auth',
'pamphlet_admin',
'itsmywine.apps.accounts',
'itsmywine.apps.core',
'itsmywine.apps.static_pages',
'itsmywine.packages.text',
'itsmywine.packages.images',
'itsmywine.packages.pattern',
'itsmywine.packages.custom',
'itsmywine.packages.shop',
'rest_framework',
'provider',
'provider.oauth2',
'debug_toolbar')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/provider/views.py" in dispatch
41. response = super(OAuthView, self).dispatch(request, *args, **kwargs)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/provider/views.py" in post
285. return self.handle(request, request.POST)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/provider/views.py" in handle
277. self.cache_data(request, client.serialize(), "client")
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/provider/oauth2/models.py" in serialize
56. return dict(user=serialize_instance(self.user),
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/provider/utils.py" in serialize_instance
81. return json.loads(json.dumps(ret, cls=DjangoJSONEncoder))
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
250. sort_keys=sort_keys, **kw).encode(obj)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
207. chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in iterencode
270. return _iterencode(o, 0)
File "/usr/local/var/virtualenvs/itsmywine/lib/python2.7/site-packages/django/core/serializers/json.py" in default
104. return super(DjangoJSONEncoder, self).default(o)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /oauth2/authorize/confirm
Exception Value: <ImageFieldFile: uploads/users/1406301951.e25eee345552ad7736f1bae3f3c0819c.jpg> is not JSON serializable
Hello!
I followed step described here https://django-oauth2-provider.readthedocs.org/en/latest/getting_started.html
and also here http://blog.ansals.me/2014/12/04/building-an-oauth2-provider-in-django/
But when I use in command line of ubuntu
curl -X POST -d "client_id=test_id&client_secret=test_secret&grant_type=password&username=user1&password=user1R_PASSWORD" http://localhost:8001/oauth2/access_token/
Nothing is returning. Only the text of "it worked! your first django site etc" Am I missing something? Also my django version is 1.4
Thank you
In the ScopeChoice Field class in provider/oauth2/forms.py, the scope choice is no longer parsed correctly, so it raises an invalid_request. Writing something like
value = value.split('\s')
in line 60 (instead of raise OAuthValidationError....) fixes the problem
In 'provider/views.py' at line 303, "if 'state' in data" always equates to True, as even if no value is supplied with the request, data['state'] returns an empty string
if 'state' in data:
query['state'] = data['state']
This results in 'state=&code=some_code' always being returned in the redirect url
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.