源码

如何在Laravel中验证HTTP请求

我有一个iOS应用程序正在向使用Laravel的服务器点发出HTTP请求/uff0c一切正常。但我想在返回信息之前验证HTTP请求。 现在它的工作方式是键入example.com/zip-code/51751/uff0c服务器响应请求/uff0c但我想要的是让服务器只响应来自iOS应用程序的请求。 我在想的是在我的iOS应用程序中对随机密钥进行硬编码/uff0c然后将该密钥作为我的HTTP请求的一部分包含在内/uff0c以便我可以检查请求以查看密钥是否在 请求与服务器中的密钥匹配/uff08.env文件/uff09。
这是我目前拥有的代码/uff1a

Routes File

Route::get('zip-code/{zipCode}', 'MyController@placeDescription');

Controller

class MyController extends Controller
{
    public function placeDescription($zipCode)
    {     
        $placeInfo = InfoDB::where('ZipCode', $zipCode)->get();
        return ($placeInfo);
    }
}

.env File

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:GpyF4XKuxMqCfkylHfdsfFDSjfasdfFDgfsdGfdsFGffhg=
APP_URL=http://localhost

LOG_CHANNEL=stack
DB_CONNECTION=sqlite
...

iOS App / Swift

func descriptionForCurrentLocation(zipCode: String, completion:@escaping(_ placeDescription:String?) -> () ){

    let siteLink = "http://example.com/zip-code/" + zipCode
    let url = URL(string: siteLink)

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in

        guard error == nil else {
            // ERROR
            completion(nil)
            return
        }
        guard let data = data else {
            // Return, data is empty 
            completion(nil)
            return
        }
        let json = try! JSONSerialization.jsonObject(with: data, options: [])

        guard let jsonArray = json as? [[String: String]] else {
            // Return, the object returned by the server is not in the right format.
            return
        }

        if jsonArray.isEmpty{
            // Return, array is empty.
            return
        }else{
            let description = jsonArray[0]["CityDescription"]!
            completion(description)
        }
    }
    task.resume()
}

如何针对随机密钥验证HTTP请求呢/uff1f

答案如下/uff1a

可以生成一个用于验证请求和验证请求的UUID/uff0c可以使用下面的代码/uff1a

use Illuminate/Http/Request;

class MyController extends Controller
{
    public function placeDescription(Request $request, $zipCode)
    { 
       if($request->hasHeader('CustomKey') && $request->header('CustomKey') === "161jshghss")
       {
        $placeInfo = InfoDB::where('ZipCode', $zipCode)->get();
        return ($placeInfo);
       }
       else
       {
         return response(['error' => 'Something is missing'], 403);
       }  
     }
}

必须使用HeaderName和Headervalue在ios应用程序中设置自定义标题/uff0c然后您可以使用上面的代码。

(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/ruhezailaravelzhongyanzhenghttpqingqiu.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:8 月 25, 2019 at 08:43 下午

热评文章