iosswiftlaravelpost

How to use authentication method to access Laravel API with Swift?


I'm developing iOS App I made POST API myself. Now, when I press the button from iOS, I create a function to access API and post value. I tried to input the value to test the API once with PostMan, but I got an error:

The page has expired due to inactivity.

I understand that this error is because POST does not include csrf_token.

If you use csrf_token on iOS to authenticate, what is the way to authenticate? Also, are there other authentication methods?

Swift Button function

@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 FavoriteController

public function favorite(Request $request){

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

Laravel routes/web.php

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

Solution

  • Excluding URIs From CSRF Protection Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

    Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

    <?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/*',
        ];
    }
    

    Note:Apis should be stateless .Better use jwt for authentication and also csrf token only for web interface not for apis

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

    if you are using latest version laravel then you have api.php instead of web.php for apis

    if you still want to use web.php then you can exclude csrf token in VerifyCsrfToken

      protected $except = [
                '/*',
    
            ];
    

    I recommend you add your routes in routes/api.php so that you dont get csrf token issue.Also you need to add api in your urls

    http://localhost:8080/api/yourroutename