Comments (15)
The way it currently works is we use your User's model USERNAME_FIELD
. If you just want to use another field for authentication you can implement your own class of JSONWebTokenSerializer
like:
class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'email'
from django-rest-framework-jwt.
Could this information be adde to the Readme?
Alternatively, (and I think it is cleaner), can there be another API for
getting a token based on username/email address without the user specifying
which one it is?
On Sep 17, 2014 10:02 AM, "José Padilla" [email protected] wrote:
The way it currently works is we use your User's model USERNAME_FIELD. If
you just want to use another field for authentication you can implement
your own class of JSONWebTokenSerializer like:class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'email'Reply to this email directly or view it on GitHub
#34 (comment)
.
from django-rest-framework-jwt.
@syedsaqibali I think it's time to have some more formal docs. So i'll have this in mind.
Do you have any suggestions on how this should be?
from django-rest-framework-jwt.
I don't think you should use a serializer at all. We can't know which fields are needed for a given (custom?) backend unless we hard-code them. I suggest you could directly do authenticate(**request.DATA), so that any credentials combination can work
from django-rest-framework-jwt.
@jpadilla Do I have to fork the whole app and use my own implementation if I wanted email authentication? Or is there a way to just use my own class with the default code?
from django-rest-framework-jwt.
@aganhuyag you should be able to implement your own custom view extending from ObtainJSONWebToken
that uses your own serializer. You could also try something like I mentioned in #34 (comment).
I haven't tried this myself, so if anyone wants to share their solution that'd be great.
from django-rest-framework-jwt.
👍 for getting a token based on username/email address without the user specifying
which one it is, or if we can specify in the config which field to use or both
from django-rest-framework-jwt.
I'd be happy to check out pull requests for this. Currently not a pressing issue for me. If anyone wants to tackle it, go right ahead. I'll help out however I can.
from django-rest-framework-jwt.
@syedsaqibali @aganhuyag I use email/password for authentication and I haven't needed to do anything special. As @jpadilla mentioned above, the django documentation states that you use the USERNAME_FIELD on a subclass of AbstractUser to specify your own identifier field.. Set that to 'email' and thats all you should need to do
from django-rest-framework-jwt.
Well, my workaround is to have the user enter data into a field named username_or_email. Then I check that entry to see if it contains a "@". If it does, then I look that email address up in the User table and get the username. Otherwise, I take what they gave me as the username. Then I login with the (possibly derived) username and password.
from django-rest-framework-jwt.
@syedsaqibali interesting.. which version of django do you use? are you allowing users to use either email OR a custom username? in my current app Im building I actually use email as the identifier but I also automatically generate a unique username based on their first + last name so you can do pretty url's eg. myapp.com/people/barrackobama
from django-rest-framework-jwt.
@ericonkanen Django version 1.7.1
Yes. I am allowing my users to login with their email OR their username. I think its more elegant that way.
I also have the same requirements in my app as you to make the URL pretty and readable. However. I wouldn't advise at all the way you are doing it. If their name has special or non-English characters, you will run into all kinds of problem. What I did instead was to create a new model called "Profile" which looks like this:
from autoslug import AutoSlugField
class Profile(models.Model):
user = models.OneToOneField(User)
slug = AutoSlugField(
populate_from='username',
always_update=True,
unique=True,
)
To get the AutoSlugField
package I did:
$ pip install django-autoslug-field
Now, to make my URLs pretty, I use Profile.slug. It's guaranteed to be a reasonable length and safe to use in a URL. Try it! Also, using my own Profile class instead of Django's User model allows me to more easily add custom fields to this model.
from django-rest-framework-jwt.
@syedsaqibali interesting, I'll check that out!.. I do have some filters on it, e.g. first and last names can only be alphanumeric (letters/numbers), and if there is a name collision, it appends a number to the end... e.g. /people/bobsmith.39 (got that idea from graph.facebook.com/)
from django-rest-framework-jwt.
Closing this for lack of activity. Will reopen if there are concrete actions for a next step.
from django-rest-framework-jwt.
@jpadilla As per your suggestion of making a Customize Serializer, i've implemented the same as below which works absolutely fine:
This works for 'username_or_email' and 'password' fields where the user can enter its username or email and get the JSONWebToken for correct credentials.
class CustomJWTSerializer(JSONWebTokenSerializer):
username_field = 'username_or_email'
def validate(self, attrs):
password = attrs.get("password")
user_obj = User.objects.filter(email=attrs.get("username_or_email")).first() or User.objects.filter(username=attrs.get("username_or_email")).first()
if user_obj is not None:
credentials = {
'username':user_obj.username,
'password': password
}
if all(credentials.values()):
user = authenticate(**credentials)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
payload = jwt_payload_handler(user)
return {
'token': jwt_encode_handler(payload),
'user': user
}
else:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "{username_field}" and "password".')
msg = msg.format(username_field=self.username_field)
raise serializers.ValidationError(msg)
else:
msg = _('Account with this username or email does not exists')
raise serializers.ValidationError(msg)
return super(CustomJWTSerializer, self).validate(attrs)
from django-rest-framework-jwt.
Related Issues (20)
- Is there a way that we can avoid multiple token generations for a single user if he/she try to login on different browsers? HOT 2
- JSONWebTokenAuthentication object has no attribute 'media_type'
- external server
- Call an endpoint without Authorization header HOT 1
- Add support for ES256 signing algorithm
- [feature] permit to use custom header instead of `Authorization`
- registration
- how to refresh existing tokens??? HOT 6
- redis cache HOT 1
- WinError 123 after tutorial HOT 1
- How to use this library by only using Http Only Cookie? HOT 1
- Curious Whether JWT Still Works Given Libraries Requirements Mismatch? HOT 3
- Status HOT 12
- Documentation not found HOT 2
- Dead Link in readme.md HOT 1
- DeprecationWarning: The following fields will be removed in the future: `email` and `user_id`. HOT 1
- Hope to support the response format of custom authentication failure HOT 1
- Unreachable code when user is_active is False in. HOT 1
- Can we use allauth only for the things, where we can get involved with email verification, and jwt for others purposes like login/get api request/ post api requests....????
- Cookie not removed in request when response is 401
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-rest-framework-jwt.