我有两个字符串
$password_api = VSE::user('password',$username); //abc
$password = Input::get('password'); //abc
如果它们匹配,我想在中记录用户
if ( $password == $password_api ) {
// Not sure what to do in here ...
$auth = Auth::attempt();
}
限制:
我没有Laravel user model
或users table
。这一切都是通过API调用实现的。
我如何在Laravel 5中做到这一点?
我希望这能帮助
在这里,我假设您有一个包含用户数据的"users"表。您的api用户名与"users"表用户名字段相同。
控制器功能
public function login()
{
$password_api = VSE::user('password',$username);
$password = Input::get('password');
if ( $password == $password_api ):
if (Auth::attempt(['username' => $username, 'password' => $password])) {
// Authentication passed...
}
else{
// Authentication failed...
}
endif;
}
如果您没有"用户"表
我认为最简单的方法是在密码匹配时创建一个会话值,并为该auth创建一个中间件/过滤器。
控制器功能
public function login()
{
$password_api = VSE::user('password',$username);
$password = Input::get('password');
if ( $password == $password_api ):
Session::put('api_auth','1')
endif;
}
检查用户是否已登录
if(Session::get('api_auth')==1):
//logged in
endif;
中间件创建
参考http://laravel.com/docs/5.0/middleware更多信息
<?php
namespace App'Http'Middleware;
use Closure;
use Session;
class apiAuth
{
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Session::get('api_auth') == 1) {
return $next($request);
}
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
//no authentication';
return redirect()->route('login.page')->with('error','you need to login to view the page you requested');
}
}
}
我假设您有一个正在实现Authenticatable
合同的用户模型。
如果是这样的话,你可以做以下事情:
$user = User::where('username', '=', 'johndoe'); // find by username
Auth::login($user);
您也不必将Auth
分配给一个变量就可以实现这一点。完成登录调用后,您可以重定向用户或在应用程序中执行任何必须执行的操作。
基本身份验证
Laravel的Auth
提供身份验证服务
Auth::attempt([
'username' => Input::get('username'),
'password' => Input::get('password')
]);
如果身份验证成功,attempt
方法将返回true。
记住在类use Auth;
的顶部包含Auth facade
使用Auth
将有助于通过应用程序访问已验证用户的详细信息
例如:Auth::user()->id
会在应用程序的任何位置为您获取Auth用户id。
请参阅:Laravel认证文档
希望这对有帮助
哇,伙计,你走错了路——你不想向API询问密码——你想让API验证身份验证。向API发送密码和用户名,API会告诉你是否正确-然后API会让你登录。我建议你看看这个oauth2项目;https://github.com/lucadegasperi/oauth2-server-laravel/wiki/Laravel-5-Installation