Why does django have both an authenticate method and a login method?

↘锁芯ラ 提交于 2021-02-10 14:13:52

问题


I'm going through an authentication tutorial and the author is using the authenticate() method to authenticate the credentials data from a login form. The result is assigned to a user variable like so

user = authenticate(username=username, password=password)

next: The user is logged in using login(request, user)

But why the 2 different methods? Isn't authenticating credentials supposed to be part of the procedure of loggin in? So why isn't that part handled by the login function as well? Or are there scenario's where you do want to use authenticate but not login ?

Also, what happens when the credentials are bad? Will user become null or will an exception be thrown?

Thank you


回答1:


authenticate(..) [Django-doc] will verify credentials. It thus looks if the authentication backend has a user with the given credentials, and if so, return that User objects. Otherwise it will return None. But it will not log in that user. You can thus use that for sensitive methods, for example ask the password of a user that is already logged in, when that user plans to remove their account.

login(..) [Django-doc] on the other hand, logs in a user. It will create a session with that user, and set the correct session variables. Note that no credentials are necessary for this. You can for example use that to give an administrator access to an account ("impersonate"), or to share a "virtual account" among certain people. Logging in a user does not per se requires to authenticate first.

While the two are thus much related, and one often sees a pattern where first a user is authenticated, and then logged in, that is not necessarily the case.




回答2:


authenticate confirms a user's credentials and returns the user object. You have now resolved a set of credentials to a user object. That does not automatically mean that you want to make that user the currently logged in user too. That is what login does, it updates the session to make that user "the logged in user". Often you'll probably want to do those two things together, but not necessarily. You may want to log in a specific user without any credentials, and you may want to verify a user's credentials without necessarily logging them in.



来源:https://stackoverflow.com/questions/59412525/why-does-django-have-both-an-authenticate-method-and-a-login-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!