I am using Django rest API and trying to authenticate a user with username and password (obtain token pairs) with simpleJWT. In my settings.py I have added
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
my urls.py is as below
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/', TokenObtainPairView.as_view(), name ='token_obtain_pair'),
path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name ='token_refresh'),
]
However when I send a request to authenticate (register) a user and obtain token for that user it seems like it tries to verify the user instead and gives me the following error
{
"detail": "No active account found with the given credentials"
}
I have read multiple other related questions but nothing helped. What should I do to obtain a token for an email address and password?
Related
when i trying to access api i'm getting this error:
"detail": "Authentication credentials were not provided."
i have included this in settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
my app api urls.py:
from django.urls import path,include
from . import views
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'',views.UserViewSet, 'user_list')
urlpatterns = router.urls
my views.py:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.object.all()
serializer_class = serializers.UserSerializers
serializers.py:
from rest_framework import serializers
from users.models import User
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email','password')
my main urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(urls)),
path ('', include(user_urls)),
path('api/',include(api_urls)),
when i running localhost:8000/api i'm getting the error
You can't access the api from the browsers url if you are using TokenAuthentication.
as said by #DarkOrb TokenAuthentication expects a authorization header with token as it's value.
So You must pass token whenever you call the api.
You can test your api using postman.
In above image i have passed token in headers of postman to access my api.
When you call your api from frontend side,pass your token along with the request.
If you just want to use your api in only desktop's browser,in that case you can use SessionAuthentication only.For mobile devices Tokenauthentication must be done.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
use this in your settings.py file, what is happening is that rest_framework.authentication.TokenAuthentication expects a authorization header with token as it's value, but you can't send that with your browser, to browse API from browser you must have SessionAuthentication enabled.
I'm developing a Django application for Windows with Pyhton 2.7.15. I need to implement an authentication mechanism where if a user has a specific JWT token, he can browse the application (in other words, I just need to verify the token and not generate it). The token is very easy and maybe will be something like this:
Header
{
"alg": "HS256",
"typ": "JWT"
}
Payload
{
"iss": "customIssuer"
}
Signature
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
To implement the verification's service, I installed the Rest framework JWT tools and I modifyed my setting.py in this way:
...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.TokenAuthentication'
),
}
JWT_AUTH = {
'JWT_ISSUER': 'customIssuer'
}
...
then I modifyed the urls.py:
...
from rest_framework_jwt.views import verify_jwt_token
urlpatterns = [
...
url(r'^api-token-verify/', verify_jwt_token),
...
]
Finally, using Postman, I tryed to send a POST request with the above token but I get a 400 Bad Error error with this body:
{
"non_field_errors": [
"Invalid payload."
]
}
Investigating about the reason I realize that I must add the username claim in the payload but I don't want to. It's possible to configure the application to ignore that claim?
I am facing some problem while working with django-allauth. I am using google authentication with the help of django-allauth. I have set the redirect url in the google api console as directed in the official documentation.Also, I have set the LOGIN_REDIRECT_URL as stated in the documentation.
Authorized redirect url in google api console:
http://127.0.0.1:8000/accounts/google/login/callback/
Settings.py
LOGIN_REDIRECT_URL = "user_dashboard"
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
'hd': 'xxx.yyy'
}
}
}
urls.py
url('^', include('django.contrib.auth.urls')),
url(r"accounts/profile/logout", views.my_logout, name="logout"),
url(r'^accounts/',include("allauth.urls")),
url(r'^admin/', admin.site.urls),
url(r'^admin/inventory_management_app/device/router_specifications/', views.pdf_download, name = "pdfdownload"),
url(r'^admin/inventory_management_app/repair/repair_invoice/', views.repair_pdf_download, name = "pdfdownload"),
url(r'accounts/profile/home',views.my_dashboard,name='user_dashboard'),
url(r'accounts/profile/user_dashboard', views.my_dashboard, name = "user_dashboard"),
I get a social network authentication failure. I overrode the authentication_error.html to find the cause but, still did not get any workable response.
requesting your help at the earliest.
my view
class ldata(APIView):
def get(self, request):
data = "my name"
return Response(data)
i can confirm, every time i login using google, it successfully register the user to auth_user & social_auth_usersocialauth table.
but i am getting this error when i access the view.
{
"detail": "Authentication credentials were not provided."
}
i have configured everything said here https://github.com/RealmTeam/django-rest-framework-social-oauth2
and added few code to settings for google login
AUTHENTICATION_BACKENDS = (
# for Google authentication
'social_core.backends.open_id.OpenIdAuth',
'social_core.backends.google.GoogleOpenId',
'social_core.backends.google.GoogleOAuth2',
'rest_framework_social_oauth2.backends.DjangoOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "***"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "***"
my login call url: http://localhost:8000/auth/login/google-oauth2/
eidts:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework_social_oauth2.authentication.SocialAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
I have a REST API created with Django rest framework. To authenticate my API calls I am using OAuth2 tokens. My question is how can I enable standard username/password authentication in docs generated by Django rest swagger.
Right now i am gettings
401 : {"detail":"Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi
settings
REST_FRAMEWORK = {
# Don't perform any authentication on API calls so we don't have any CSRF problems
# :PRODUCTION: Put back authentication for production version when not testing on same server?
'DEFAULT_AUTHENTICATION_CLASSES': [
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
'rest_framework_social_oauth2.authentication.SocialAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'PAGE_SIZE': 1000, # Max number of results returned from a list API call
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
# Use JSONRender so the Web API interface is not shown. This is needed when testing the app on the same server
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'veeu': {
'type': 'oauth2',
'flow': 'password',
'tokenUrl': 'http://localhost:8000/auth/token/',
'scopes': {
'write:all': 'Write all',
'read:all': 'Read all',
}
}
},
}
LOGIN_URL = 'http://localhost:8000/admin/'
When I click Django login it takes me to admin login page. And after I log in, this message is still the same. If I add header Authorization: Bearer TokenHere it works. However, the point is to enable username/password login.
To access Swagger documentation, you need SessionAuth with the following in the settings.py :
# API VERSIONING
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
}
This allows you to access Swagger generated documentation. Problem is, whatever endpoint you have protected with OAuth2 won't be visible via Swagger, at least if you are generating OAuth via "application". The following code does not work at all and I'm linking the thread discussed asking for anyone to work on that feature:
# TODO Swagger implementation is not working for password since
# it sends client_id and client_secret as query strings and not as
# user separated with "::"
# The "application" flow setting also that does work
#
SWAGGER_SETTINGS = {
'SUPPORTED_SUBMIT_METHODS': [], # Due to bug described above
'SECURITY_DEFINITIONS': {
"customers_auth": {
"type": "oauth2",
"tokenUrl": "/o/token/",
"flow": "password",
"scopes": {
"read": "Read scope",
"write": "Write scope"
}
}
},
}