【问题标题】:Laravel 5.5 Request ValidationsLaravel 5.5 请求验证
【发布时间】:2018-09-15 04:24:22
【问题描述】:

我有来自 Web 和 API 的登录功能。我创建了一个请求文件,并为此编写了规则。对于网络,它运行良好并按预期给出输出,但是当我在 API 控制器中使用它时,它会将我重定向到登录页面,它应该返回 JSON 响应。

还有一件事,我想在失败或成功时添加额外的参数“status”。

这是我的代码 请求文件

public function rules()
    {
        return [
            'username' => 'required',
            'password' => 'required'
        ];
    }

API 控制器

public function login(Request $request)
{
    $response = array();
    $validator = Validator::make($request->all(), [
        'username' => 'required',
        'password' => 'required'
    ]);

    if ($validator->fails()) {
        $response['status'] = false;
        $response['message'] = $validator->messages();
        return Response::json($response);
    }

    try {
        $username = trim($request->username);
        $password = trim($request->password);

        $isAuth = $this->userRepository->login($username, $password);
        if ($isAuth) {
            $user = Auth::user();
            $response['status'] = true;
            $response['message'] = Lang::get('custom.auth_success');
            $response['user_detail'] = $user;
        } else {
            $response['status'] = false;
            $response['message'] = Lang::get('auth.failed');
        }
    } catch (\Exception $e) {
        $response = array();
        $response['status'] = false;
        $response['message'] = Lang::get('custom.something_wrong');
    }
    return Response::json($response);
}

和网络控制器

 public function checkAuth(UserAuthenticate $request)
{
    try {
        $username = trim($request->username);
        $password = trim($request->password);
        $isRemember = false;
        if (isset($request->remember) && $request->remember == 'on') {
            $isRemember = true;
        }

        $isAuth = $this->userRepository->login($username, $password, $isRemember);

        if ($isAuth) {
            return redirect('programs');
        } else {
            return redirect('login')->withInput()->withErrors(['username' => Lang::get('auth.failed')]);
        }
    } catch (\Exception $e) {
        return redirect('login')->withInput()->withErrors(['error' => Lang::get('custom.something_wrong')]);
    }
}

路由/web.php

Route::group(['middleware' => ['guest']], function () {
    Route::get('login', ['as' => 'login', 'uses' => 'Front\UserController@login']);
});

路由/api.php

Route::post('user/authenticate', 'API\UserController@login');

我寻找解决方案,但没有找到任何东西

【问题讨论】:

  • 您的 API 路由使用什么身份验证机制?你能告诉我们你的 api 路线吗?
  • @user3574492,我更新了我的问题并为 web 和 api 添加了路由文件代码
  • 你用护照认证吗
  • @afsalc,是的。但是我在 API 中间件中添加了这些路由。登录路由不在 API 中间件中
  • 请分享public function login(UserAuthenticate $request){}的完整代码?

标签: laravel api laravel-5.5


【解决方案1】:

编辑:如果您想对两个验证器都使用扩展请求,请通过 ajax 进行网络验证

  1. 由于您使用的是护照,因此您已经拥有令牌,因此您可以跳过登录

  2. 对于 api,您的验证器需要扩展 Request 而不是 FormRequest

您不能使用相同的验证器,因为网络验证器扩展了 FormRequest 并返回 html。需要两个验证器,没有办法绕过它。

use App\Http\Requests\Request;
  class YourApiRequest extends Request
  {
      /**
       * Determine if the user is authorized to make this request.
       *
       * @return bool
       */
  public function authorize()
  {
      return true;
  }

      /**
       * Get the validation rules that apply to the request.
       *
       * @return array
       */
      public function rules()
      {}....

在您正常的网络请求中,您将拥有

use Illuminate\Foundation\Http\FormRequest;
 class YourWebRequest extends FormRequest
 {
 /**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
 public function authorize()
 {
 // only allow updates if the user is logged in
 return \Auth::check();
 }

 /**
* Get the validation rules that apply to the request.
*
* @return array
*/
 public function rules()
 {....
  1. 在 Handler.php 中,你需要在 render 方法中添加一些东西(如果你从你的 api 返回 json)

    如果你没有为你的路由添加前缀 api/ 那么想办法检查你是否在 api 中

if (strpos($prefix, 'api') !== false) {
            if ($exception instanceof ValidationException) {
                return response()->json(['success' => false, 'error' => $exception->errors(), 'data' => null], 200);
            }
            return response()->json(['success' => false, 'error' => $exception->getMessage(), 'data' => null], 200);
        }

【讨论】:

    【解决方案2】:

    您可以尝试覆盖 Laravel 表单请求验证failedValidation() 方法。

    public function failedValidation(Validator $validator)
    {
        //wantsJson() that checks Accept header of the request and returns TRUE if JSON was requested.
        if ($this->wantsJson()) {
            throw new HttpResponseException(response()->json(["response" => [
                'msg'    => $validator->errors()->all(),
            ]]));
        }
    }
    

    [未在 api 调用上测试]

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 2018-06-30
      • 1970-01-01
      • 2018-06-16
      • 2018-06-03
      • 2017-11-21
      • 2020-01-13
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多