Laravel 5.2-使用新的\ App \ User时不保留Auth :: login [英] Laravel 5.2 - Auth::login not preserve when using new \App\User

查看:72
本文介绍了Laravel 5.2-使用新的\ App \ User时不保留Auth :: login的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用这些代码从外部来源验证用户名而不使用数据库,但是laravel 5.2无法保存身份验证,并且每次都请求外部来源.

I've used these code to authenticate username from external source without using database, but laravel 5.2 not save the authentication, and request the external source every time.

class Authenticate
{
    public function handle($request, Closure $next, $guard = null)
        {
            if (Auth::guard($guard)->guest()) {
                if ($request->ajax()) {
                    return response('Unauthorized.', 401);
                } else {
                    $username = getFromExternalSource();
                    if($username==null){ redirect()->guest('auth/login'); }
                    $user = new \App\User(['username'=>'admin']);
                    Auth::login($user);
                }
            }

            return $next($request);
        }
}

但是当我使用$ user模型更改Auth :: login从数据库中获取它的功能时,我不知道为什么:

But when I change Auth::login using $user model get from database it work, I don't know why:

$userDB = \App\User::where('username','=','admin')->first();
Auth::login($userDB);

我的路线(例如,我想访问 http://myApp/api )

My route (for example I want to access http://myApp/api)

Route::group(['middleware' => ['web']], function () {
    Route::group(['middleware' => 'auth'], function () {
        Route::get('api/', 'ApiController@index');
    });
    Route::group(['middleware' => ['csrf']], function () {
       Route::controllers([
           'auth' => 'Auth\AuthController',
           'password' => 'Auth\PasswordController'
       ]);
   });

});

推荐答案

据我所知,默认的身份验证方法需要传递数据库中存在的模型.在您的示例中,您只创建了一个对象,并为其分配了 username 属性.

As far as I know for default authenticate method, you need to pass model that exists in database. In your example you created just object and assigned to it username property.

如果您需要验证所选用户的身份,则应使用:

If you need to authenticate selected user, you should use:

Auth::loginUsingId($id);

(在 $ id 位置,您应该传递要验证的用户的ID-在这种情况下,用户名为 admin 的用户的ID)

(where in place of $id you should pass id of user you want to authenticate - in your case id of user with username admin)

这篇关于Laravel 5.2-使用新的\ App \ User时不保留Auth :: login的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆