Laravel 5.5请求验证

时间:2018-04-05 11:04:00

标签: laravel api laravel-5.5

我有来自Web和API的登录功能。我创建了一个请求文件,我已经为此编写了规则。对于web,它正常工作并按预期输出,但是当我在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);
}

和Web控制器

 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');

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

2 个答案:

答案 0 :(得分:0)

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

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

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

  3. 您无法使用相同的验证程序,因为Web验证程序会扩展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

    2. 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);
              }
      

答案 1 :(得分:0)

您可能会试图超越 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电话上测试]