[英]cakephp auth getuser in beforefilter
in my cakephp app with custom auth implementation (see here ) i would like to check the auth of a user in the beforefilter method and if he/she is not authenticated i would like to manually render an error page and quit.在我的带有自定义身份验证实现的 cakephp 应用程序中(参见此处),我想在 beforefilter 方法中检查用户的身份验证,如果他/她未通过身份验证,我想手动呈现错误页面并退出。 My problem here is that it seems the auth object gets only filled with data AFTER the action call to an action which require auth.
我的问题是,似乎 auth 对象仅在对需要身份验证的操作的操作调用之后才填充数据。 i would need to access auth data in my beforefilter function.
我需要在我的 beforefilter 函数中访问身份验证数据。 how to achieve this?
如何实现这一目标? if i try to access it auth->user() it returns NULL, loggedIn() returns always false (because there is no data, makes sense)
如果我尝试访问它 auth->user() 它返回 NULL,loggedIn() 总是返回 false(因为没有数据,这是有道理的)
There's no need to check yourself whether a user is authenticated and show error page.无需自行检查用户是否已通过身份验证并显示错误页面。 Just add a
unauthenticated()
method to your custom authenticate class like the BasicAuthenticate class does (without setting the headers).只需像BasicAuthenticate类那样向您的自定义身份验证类添加一个
unauthenticated()
方法(无需设置标头)。 The error handler using the exception renderer will generate appropriate error page.使用异常渲染器的错误处理程序将生成适当的错误页面。
I stumbled upon this question and the proposed solution did't work for me.我偶然发现了这个问题,建议的解决方案对我不起作用。
The proper way to get auth information in beforeFilter in Cakephp 3 is to call在 Cakephp 3 中的 beforeFilter 中获取身份验证信息的正确方法是调用
$this->Auth->config('checkAuthIn', 'Controller.initialize');
right after loading the auth component.在加载 auth 组件之后。 This is especially useful in stateless authentication scenarios (eg token authentication).
这在无状态身份验证场景(例如令牌身份验证)中特别有用。
You can then get user information in beforeFilter by calling然后就可以在beforeFilter中通过调用获取用户信息
$user = $this->Auth->user();
See the docs http://book.cakephp.org/3.0/en/controllers/components/authentication.html#deciding-when-to-run-authentication请参阅文档http://book.cakephp.org/3.0/en/controllers/components/authentication.html#deciding-when-to-run-authentication
class CustomAuthenticate extends BaseAuthenticate {
public function authenticate(CakeRequest $request, CakeResponse $response) {
// Return an array of user if they could authenticate the user,
// return false if not
}
}
you authenticate
method should return an array with the user data.您的
authenticate
方法应该返回一个包含用户数据的数组。 From your link to the other question it seems that it doesn't从你的链接到另一个问题似乎没有
在 CakePHP 2.x 中,这可以解决问题
$this->Auth->startup($this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.