1646322986
Trong hướng dẫn này Chúng tôi sẽ chỉ cho bạn cách tải tệp lên qua api bằng cách sử dụng postman trong laravel 9 với xác thực.
Làm theo các bước đơn giản dưới đây để tải tệp lên trong laravel 9. ứng dụng
Trong bước 1, mở thiết bị đầu cuối của bạn và điều hướng đến thư mục máy chủ web cục bộ của bạn bằng lệnh sau:
//for windows user
cd xampp/htdocs
//for ubuntu user
cd var/www/html
Sau đó cài đặt ứng dụng laravel mới nhất bằng lệnh sau:
composer create-project --prefer-dist laravel/laravel LaravelApiFile
Ở bước 2, mở ứng dụng laravel đã tải xuống của bạn vào bất kỳ trình soạn thảo văn bản nào. Sau đó tìm tệp .env và định cấu hình chi tiết cơ sở dữ liệu như sau:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Trong bước 3, mở dấu nhắc lệnh và điều hướng đến dự án của bạn bằng cách sử dụng lệnh sau:
cd / LaravelApiFile
Sau đó, tạo mô hình và tệp di chuyển bằng cách sử dụng lệnh sau:
php artisan make:model File -m
Lệnh trên sẽ tạo hai tệp vào ứng dụng hướng dẫn tải lên tệp laravel của bạn, nằm bên trong các vị trí sau:
Vì vậy, hãy tìm tệp create_files_table.php bên trong thư mục / database / migrations / . Sau đó, mở tệp này và thêm mã sau vào hàm up () trên tệp này:
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('path');
$table->timestamps();
});
}
Bây giờ, hãy mở lại thiết bị đầu cuối của bạn và nhập lệnh sau vào cmd để tạo bảng vào cơ sở dữ liệu đã chọn của bạn:
php artisan migrate
Trong bước 4, mở tệp api.php của bạn, nằm bên trong thư mục các tuyến đường. Sau đó, thêm các tuyến sau vào tệp web.php:
use App\Http\Controllers\API\FileUploadController;
Route::post('uploading-file-api', [FileUploadController::class, 'upload']);
Trong bước 5, tạo bộ điều khiển tải lên tệp API bằng cách sử dụng lệnh sau:
php artisan make:controller API\FileUploadController
Lệnh trên sẽ tạo tệp FileUploadController.php , nằm bên trong thư mục / app / Http / Controllers / API .
Các quy tắc xác thực laravel sau đây sẽ xác thực tệp trước khi tải lên / lưu vào cơ sở dữ liệu:
$validator = Validator::make($request->all(),[
'file' => 'required|mimes:doc,docx,pdf,txt,csv|max:2048',
]);
if($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
Lưu ý rằng, nếu bạn muốn upload file ảnh qua api bằng cách sử dụng postman. Vì vậy, bạn có thể làm điều đó bằng cách thêm các quy tắc xác thực sau với $ validator:
'file' => 'required|mimes:png,jpg,jpeg,gif|max:2048',
Sau đó, thêm mã đã cho bên dưới vào tệp API \ FileController.php:
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\File;
use Validator;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
public function upload(Request $request)
{
$validator = Validator::make($request->all(),[
'file' => 'required|mimes:doc,docx,pdf,txt,csv|max:2048',
]);
if($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
if ($file = $request->file('file')) {
$path = $file->store('public/files');
$name = $file->getClientOriginalName();
//store your file into directory and db
$save = new File();
$save->name = $file;
$save->store_path= $path;
$save->save();
return response()->json([
"success" => true,
"message" => "File successfully uploaded",
"file" => $file
]);
}
}
}
Một dòng mã sau sẽ tải lên các tệp bên trong thư mục lưu trữ / ứng dụng / công khai / tệp :
$path = $request->file('file')->store('public/files');
Cuối cùng, mở lại dấu nhắc lệnh của bạn và chạy lệnh sau để khởi động máy chủ phát triển để tải lên tệp laravel của bạn thông qua ứng dụng api:
php artisan serve
Trong bước 7, mở ứng dụng người đưa thư và gọi api với tham số tệp:
http://127.0.0.1:8000/uploading-file-api
Tệp tải lên qua api bằng người đưa thư sẽ giống như sau:
Lưu ý rằng, trong ví dụ này, tệp sẽ được tải lên trên đường dẫn sau - lưu trữ / ứng dụng / công khai / tệp .
Bây giờ bạn có thể tải tệp lên qua api bằng cách sử dụng bưu tá trong laravel 9 với xác thực.
1595240610
Laravel 7 file/image upload via API using postman example tutorial. Here, you will learn how to upload files/images via API using postman in laravel app.
As well as you can upload images via API using postman in laravel apps and also you can upload images via api using ajax in laravel apps.
If you work with laravel apis and want to upload files or images using postman or ajax. And also want to validate files or images before uploading to server via API or ajax in laravel.
So this tutorial will guide you step by step on how to upload file vie API using postman and ajax in laravel with validation.
Follow the below given following steps and upload file vie apis using postman with validation in laravel apps:
Checkout Full Article here https://www.tutsmake.com/laravel-file-upload-via-api-example-from-scratch/
#uploading files via laravel api #laravel file upload api using postman #laravel image upload via api #upload image using laravel api #image upload api in laravel validation #laravel send file to api
1595396220
As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.
Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.
Most APIs provide access to resources that are lists of entities such as /users
or /widgets
. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:
First Call: GET /items?skip=0&take=10
Second Call: GET /items?skip=10&take=10
However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped
A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:
skip = 0
while True: response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip), headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]}) print("Fetched 10 items") sleep(randint(100,1000)) skip += 10
To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.
Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.
The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.
APIs are used in a way that increases the probability credentials are leaked:
If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.
The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.
The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)
APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.
The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response.
There are a variety of algorithms to do this such as leaky bucket and fixed window counters.
APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.
Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs
APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.
#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys
1601381326
We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.
The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:
With regards to how the APIs are shared:
#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway
1602036957
Laravel 8 rest api authentication with passport tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.
Step 1: Download Laravel 8 App
Step 2: Database Configuration
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller
Step 8: Now Test Laravel REST API in Postman
https://www.tutsmake.com/laravel-8-rest-api-authentication-with-passport/
#laravel api authentication with passport #laravel 8 api authentication #laravel 8 api authentication token tutorial #laravel 8 api authentication using passport #laravel 8 api authentication session
1604399880
I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.
So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.
First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.
Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.
If you desire to reproduce the examples that will be shown here, you will need some of those items below.
To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.
#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api