wagnerdelima/drf-social-oauth2

Unsupported grant type: python=3.10.2, django=3.2.4, djangorestframework=3.12.4, django-oauth-toolkit==2.1.0, drf-social-oauth2==1.2.1

Closed this issue · 2 comments

I am facing unsupported grant type (provided correct username, password, grant_type, client_id, client_secret) error when trying to get token. Tried with both curl and postman. I'm using python=3.10.2, django=3.2.4, djangorestframework=3.12.4, django-oauth-toolkit==2.1.0, drf-social-oauth2==1.2.1

I get this response (with grant_type: password):
(venv) D:\someproject>curl -X POST -d "client_id=2aZsnx7Jcdg2beAJJNIYvChVgOuLY4O9dPcH3OkD&client_secret=pbkdf2_sha256$260000$Yu4SuLFINHg8VuI0JWfR94$yGQG0cGwendBeVmfUjh8JfhiFbTaAnF8D7sAC1gveH4=&grant_type=password&username=babor@gmail.com&password=babor" http://localhost:8000/auth/token
{"error":"unsupported_grant_type"}

I get this response (with grant_type: client_credentials):
(venv) D:\someproject>curl -X POST -d "client_id=2aZsnx7Jcdg2beAJJNIYvChVgOuLY4O9dPcH3OkD&client_secret=pbkdf2_sha256$260000$Yu4SuLFINHg8VuI0JWfR94$yGQG0cGwendBeVmfUjh8JfhiFbTaAnF8D7sAC1gveH4=&grant_type=client_credentials&username=babor@gmail.com&password=babor" http://localhost:8000/auth/token
{"error":"unsupported_grant_type"}

NB: USERNAME_FIELD=email in the User model and here babor@gmail.com is a super user. Also changed the grant type in the django admin 'application' table to 'client_credentials' when sending the grant_type=client_credentials in the request.
Nothing worked for me.

My custom user model is:
class User(AbstractBaseUser):
class Gender(models.TextChoices):
MALE = 'male', _('Male')
FEMALE = 'female', _('Female')
OTHERS = 'others', _('Others')
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
username = models.CharField(max_length=100, unique=True, null=True, blank=True)
email = models.EmailField(verbose_name='email address', max_length=255, unique=True, null=True, blank=True)
user_type = models.CharField(max_length=50, null=True, blank=True)

gender = models.CharField(max_length=6, choices=Gender.choices, default=Gender.MALE)

primary_phone = PhoneNumberField(verbose_name='phone number', unique=True)
secondary_phone = PhoneNumberField(null=True, blank=True, unique=True)

date_of_birth = models.DateField(null=True, blank=True)

email_token = models.CharField(max_length=500, null=True, blank=True)
phone_otp = models.CharField(max_length=100, null=True, blank=True)

is_email_verified = models.BooleanField(default=False)
is_primary_phone_verified = models.BooleanField(default=False)

is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True, blank=True)

street_address_one = models.CharField(max_length=255, null=True, blank=True)
street_address_two = models.CharField(max_length=255, null=True, blank=True)

thana = models.ForeignKey(Thana, on_delete=models.SET_NULL, null=True, blank=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
postal_code = models.CharField(max_length=50, null=True, blank=True)

image = models.ImageField(upload_to="users/", null=True, blank=True)
nid = models.CharField(max_length=32, null=True, blank=True)

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.SET_NULL, related_name="+", null=True, blank=True)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.SET_NULL, related_name="+", null=True, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'gender']
class Meta:
	ordering = ('-id', )
def __str__(self):
	return str(self.email)
def has_perm(self, perm, obj=None):
	"Does the user have a specific permission?"
	# Simplest possible answer: Yes, always
	return True
def has_module_perms(self, app_label):
	"Does the user have permissions to view the app `app_label`?"
	# Simplest possible answer: Yes, always
	return True
@property
def is_staff(self):
	"Is the user a member of staff?"
	# Simplest possible answer: All admins are staff
	return self.is_admin
@property
def is_superuser(self):
	# Simplest possible answer: All admins are superuser
	return self.is_admin

settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

# 3rd party
'rest_framework',
'corsheaders',
'drf_spectacular',
'phonenumber_field',
'djoser',
'django_filters',
'oauth2_provider',
'social_django', 
'drf_social_oauth2',

# local
'account.apps.AccountConfig',
'authentication.apps.AuthenticationConfig',
'product.apps.ProductConfig',

'order.apps.OrderConfig',
'purchase.apps.PurchaseConfig',
'purchase_final.apps.PurchaseFinalConfig',
'site_settings.apps.SiteSettingsConfig',
'support.apps.SupportConfig',
'report.apps.ReportConfig',
'dashboard.apps.DashboardConfig',
]

INSTALLED_APPS += ['sequences.apps.SequencesConfig']

MIDDLEWARE = [
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',

'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',

'corsheaders.middleware.CorsMiddleware', # corsheaders

'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

# 3rd party
'django_currentuser.middleware.ThreadLocalUserMiddleware',

]

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

ROOT_URLCONF = 'start_project.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]

WSGI_APPLICATION = 'start_project.wsgi.application'

AUTH_USER_MODEL = 'authentication.User'

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'some',
'USER': 'some',
'PASSWORD':'12345678'
}
}

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # media files upload directory
MEDIA_URL = '/media/' # media files retrieve directory

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

WHITENOISE_USE_FINDERS = True
CORS_ALLOW_ALL_ORIGINS=True

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication', # django-oauth-toolkit >= 1.0.0
'drf_social_oauth2.authentication.SocialAuthentication',
),
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.MultiPartParser',
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
],
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
),
}
AUTHENTICATION_BACKENDS = (
'drf_social_oauth2.backends.DjangoOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
OAUTH2_PROVIDER = {
'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
}

Desktop:

  • OS: Windows 10 home

this is the application I created manually in django admin:
drf_social_oauth2_application

Hi @babor99
I was trying to reproduce your error without any success - password authentication works for me in both scenarios. Could you provide a stack-trace of the error and urls.py config?

One more thing - I've noticed you are sending client_secret hashed, in your POST request. The value should be the one you see when you create new application.

Exactly! @SukiCZ is absolutely right regarding your client secret. I am closing this issue because I also could not reproduce it successfully.