在3scale上新建了application plan之后,通过metric来限制一些api不可以访问,这样通过不同的应用计划,可以限制访问各自所需的api
api id 和 应用计划 id是hard code的
2个文件,一个是ps代码文件,一个是可以访问的metric列表,凡是不在这个列表里的,都设置为不可访问
上代码
powershell脚本
##env var
$base_url="https://xxxxxxx"
$access_token="xxxxxxxxx"
$keep_method_file="methods.txt"
##service
$service_id=111
$application_plan_id=222
##paths
$path_method_list="/admin/api/services/{service_id}/metrics/{metric_id}/methods.xml"
$path_method_create="/admin/api/services/{service_id}/metrics/{metric_id}/methods.xml"
$path_mapping_rule_create="/admin/api/services/{service_id}/proxy/mapping_rules.xml"
$path_metric_list="/admin/api/services/{service_id}/metrics.xml"
$path_service_create="/admin/api/services.xml"
$path_limit_create="/admin/api/application_plans/{application_plan_id}/metrics/{metric_id}/limits.xml"
##paras
$content_type="application/x-www-form-urlencoded"
$access_token_para="?access_token="+$access_token
##ignore self sign certificate
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$ErrorActionPreference="Stop"
##get keep methods
$keep_methods=Get-Content $keep_method_file
##get metric hits id
"get hits id"
$full_url=$base_url + $path_metric_list + $access_token_para -replace "{service_id}",$service_id
$reponse=Invoke-WebRequest -Method GET -Uri $full_url
$metric_id=([xml]$reponse.Content).metrics.metric.id
$metric_id
##list methods
$full_url=$base_url + $path_method_list + $access_token_para -replace "{service_id}",$service_id -replace "{metric_id}",$metric_id
$reponse=Invoke-WebRequest -Method GET -Uri $full_url
$reponse
$methods=([xml]$reponse.Content).methods.method
foreach($method in $methods){
if($keep_methods -notcontains $method.friendly_name){
##create limit
"create limit " + $method.friendly_name
$full_url=$base_url + $path_limit_create -replace "{application_plan_id}",$application_plan_id -replace "{metric_id}",$method.id
$body=@{
access_token=$access_token
period="eternity"
value=0
}
$reponse=Invoke-WebRequest -Method POST -Uri $full_url -body $body -ContentType $content_type
$limit_id=([xml]$reponse.Content).limit.id
$limit_id
}
}
metric列表
aaaaa bbbbb ccccc dddddd