Laravel 身份验证与雄辩的角色驱动程序
问题描述
我正在尝试对我的 Laravel 应用程序中的用户进行身份验证.
I am trying to authenticate users in my Laravel application.
我遇到了以下问题:
- 在 auth.php 中使用驱动程序数据库:我可以使用 auth::attempt() 登录,并且 auth::check 正在运行,但我无法验证登录用户是否具有特定角色.
- 在 auth.php 中使用驱动程序 eloquent:我可以使用 auth::attempt() 登录,但 auth::check 不起作用.但是,我可以检查登录用户的角色.
- using driver database in auth.php: I can login using auth::attempt(), and auth::check is working, but I can't validate if the logged in user has a certain role.
- using driver eloquent in auth.php: I can login using auth::attempt(), but auth::check is not working. I can however check the role of the logged in user.
编辑(问题):我该如何解决这个问题,以便仅使用一个驱动程序,我就可以进行完整的身份验证和角色检查?
edit (question): How can I fix this so that with only one of the drivers, i can do a complete authentication and role check?
迁移表:
模型类用户
模型类角色
HomeController 认证功能
HomeController authentication function
使用数据库驱动程序
- auth:attempt() 和 auth::check 正在工作
USING THE DATABASE DRIVER
- auth:attempt() and auth::check are working
这会因调用未定义的方法 IlluminateAuthGenericUser::hasRole()"而失败
This fails with 'Call to undefined method IlluminateAuthGenericUser::hasRole()'
EDIT 数据库 驱动程序返回一个 GenericUser 对象,我需要自己的 User 对象.不知道哪里可以改.
EDIT The database driver return a GenericUser Object, and I need my own User object. Don't know where I can change this.
解决方法:我不想使用这个,丑陋的代码和过滤器(或视图)不应该需要这样做
Workaround:I'd rather not use this, ugly code and filters (or views) should not need to do this
使用 ELOQUENT 驱动程序
USING THE ELOQUENT DRIVER
- auth::attempt() 成功
- auth::check() 失败
- 过滤器没有错误
推荐答案
问题在于您对 getAuthIdentifier()
的实现.此方法实际上应该返回表的主键,而不是用于登录的用户名.
The problem is your implementation of getAuthIdentifier()
. This method should actually return the primary key of your table and not the username that's used for logging in.
所以你的应该是这样的:
So yours should look like this:
或者实际上,我建议您多清理一下模型,因为所有 getSomeAuthStuff
方法都在两个特征中实现.
Or actually, I recommend you clean up your model a bit more since all of the getSomeAuthStuff
methods are implemented in the two traits.
使用 github 上的默认模型一个基础并添加所有自定义代码(角色方法、规则等)
Use the default model on github as a base and add all your custom code (roles methods, rules etc)
getAuthIdentifier()
返回的值将存储在会话中.
之后使用 check()
时,将在 UserProvider
上调用 retrieveById
.而 EloquentUserProvider
就是这样做的:
The value returned from getAuthIdentifier()
will be stored in the session.
When using check()
afterwards, retrieveById
will be called on the UserProvider
. And the EloquentUserProvider
does this:
它使用 find()
它通过它的主键(通常是 id
)搜索模型
It uses find()
which searches for the model by it's primary key (usually id
)
这篇关于Laravel 身份验证与雄辩的角色驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!