【问题标题】:How to use authentication method to access Laravel API with swift?如何使用身份验证方法快速访问 Laravel API?
【发布时间】:2018-09-06 15:10:36
【问题描述】:

我正在开发 iOS 应用 我自己做了 POST API。 现在,当我从 iOS 按下按钮时,我创建了一个函数来访问 APi 并发布值。 我尝试输入值以使用 PostMan 测试一次 API,但出现错误。 The page has expired due to inactivity.

我了解此错误是因为 POST 不包含 csrf_token

如果在 iOS 上使用 csrf_token 进行认证,那么认证方式是什么?另外,还有其他的认证方式吗?

快速按钮功能

@IBAction func bookmarkBtn(_ sender: Any) {
    let user_id = defaultValues.string(forKey: "id")

    let urlString = "http://127.0.0.1:8000/store/favorite"

    let request = NSMutableURLRequest(url: URL(string: urlString)!)

    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")



    let params:[String:Any] = [
        "user_id": user_id,
        "store_id" : store_id,
    ]

    do{
        request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)

        let task:URLSessionDataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data,response,error) -> Void in
            let resultData = String(data: data!, encoding: .utf8)!
            print("result:\(resultData)")
            print("response:\(response)")

        })
        task.resume()
    }catch{
        print("Error:\(error)")
        return
    }

Laravel 收藏控制器

public function favorite(Request $request){

   Favorite::create(
        array(
            'user_id' => $request->user_id,
           'store_id' => $request->store_id,
        )
    );
    return ['Status' => 'Success'];
}

Laravel 路由/web.php

Route::post('/store/favorite', 'FavoriteController@favorite');

【问题讨论】:

  • 在请求中跳过 csrf 令牌,因为在每个请求中 laravel 都会生成新的 csrf 令牌所以..

标签: ios swift laravel api post


【解决方案1】:

从 CSRF 保护中排除 URI 有时您可能希望从 CSRF 保护中排除一组 URI。例如,如果您正在使用 Stripe 处理付款并使用他们的 webhook 系统,则需要从 CSRF 保护中排除您的 Stripe webhook 处理程序路由,因为 Stripe 不会知道要向您的路由发送什么 CSRF 令牌。

通常,您应该将这些类型的路由放在 RouteServiceProvider 应用于 routes/web.php 文件中所有路由的 Web 中间件组之外。但是,您也可以通过将路由的 URI 添加到 VerifyCsrfToken 中间件的 $except 属性来排除路由:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

注意:API 应该是无状态的。最好使用 jwt 进行身份验证,并且 csrf 令牌仅用于 Web 界面而不用于 api

参考:https://laravel.com/docs/5.6/csrf#csrf-excluding-uris

如果你使用的是最新版本的 laravel,那么你有 api.php 而不是 web.php 用于 api

如果您仍然想使用 web.php,那么您可以在 VerifyCsrfToken 中排除 csrf 令牌

  protected $except = [
            '/*',

        ];

我建议你在routes/api.php 中添加你的路由,这样你就不会遇到 csrf 令牌问题。另外你需要在你的 url 中添加 api

http://localhost:8080/api/yourroutename

【讨论】:

  • 谢谢你的好回答。我成功发布数据使用 API。
  • @Alex.很高兴它帮到了你
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 2020-07-07
  • 2019-03-15
  • 1970-01-01
  • 2023-03-27
  • 2017-12-16
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多