作为程序员一定要保持良好的睡眠,才能好编程

laravel中使用hash注意事项

发布时间:2019-06-10




通过hash的make 方法加密

public function add() {
  $data = $this->getData();
  $data['password'] = Hash::make($data['password']);
  $result = $this->_Service->add($data);
  return $this->showJson($result);
}



通过 hash 的check 方法 验证密码是否正确

public function login(Request $request) {
  $platformId = $this->_input('platform_id');
  $username = $this->_input('username');
  $password = $this->_input('password');
  $adminModel = AdminModel::query()->select(['id', 'global_id', 'username', 'password', 'fullname', 'status', 'gmt_modified'])
                          ->where('username', '=', $username)
                          ->where('platform_id', '=', $platformId)
                          ->get()->first();
  if ($adminModel) {
    if (Hash::check($password, $adminModel->password)) {
      // 密码匹配
      $customClaims = ['platform_id' => $platformId, 'username' => $username, 'id' => $adminModel->id];
      $token = auth('api')->claims([CLAIMS_TOKEN => encryptData($customClaims)])->login($adminModel);
      $tokenInfo['username'] = $username;
      $tokenInfo['token'] = 'Bearer ' . $token;
      //$tokenInfo['token_type'] = 'Bearer';
      $tokenInfo['x_access_token'] = encryptData(['platform_id' => $platformId, 'time' => time()]);
      //$tokenInfo['token_name'] = 'Authorization'; //回传token名称
      return $this->showJson(returnJsonData($tokenInfo));
    } else {
      throwApiException('授权错误请重试');
    }
  } else {
    throwApiException('用户不存在或平台选择错误,请重试');
  }
}



调整 Bcrypt 加密系数


如果使用 Bcrypt 算法,你可以在 make 方法中使用 rounds 选项来配置该算法的加密系数。然而,对大多数应用程序来说,默认值就足够了:

$hashed = Hash::make('password', [
    'rounds' => 12
]);