我使用的是Swashbuckle(5.3.2),它會生成一個很好的API文檔。基於角色生成Swashbuckle API文檔/ api_key
爲了澄清我的問題,我建立了一個沒有真正意義的小例子項目。
API只能與有效的API密鑰一起使用。 爲此,我介紹了一個驗證api_key並讀出相應角色的ApiKeyFilter。
ApiKeyFilter
public class ApiKeyFilter : IAuthenticationFilter
{
private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
private readonly string authenticationScheme = "Bearer";
private readonly string queryStringApiKey = "api_key";
public bool AllowMultiple
{
get { return false; }
}
public ApiKeyFilter()
{
if (allowedApps.Count == 0)
{
allowedApps.Add("PetLover_api_key", new []{"PetLover"});
allowedApps.Add("CarOwner_api_key", new []{"CarOwner"});
allowedApps.Add("Admin_api_key", new []{"PetLover","CarOwner"});
}
}
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var req = context.Request;
Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
string rawAuthzHeader = null;
if (queryStrings.ContainsKey(queryStringApiKey))
{
rawAuthzHeader = queryStrings[queryStringApiKey];
}
else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
rawAuthzHeader = req.Headers.Authorization.Parameter;
}
if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
context.Principal = currentPrincipal;
}
else
{
context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
}
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result);
return Task.FromResult(0);
}
}
public class ResultWithChallenge : IHttpActionResult
{
private readonly string authenticationScheme = "amx";
private readonly IHttpActionResult next;
public ResultWithChallenge(IHttpActionResult next)
{
this.next = next;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await next.ExecuteAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(authenticationScheme));
}
return response;
}
}
控制器/資源只能如果請求者具有相應的角色訪問。
PetController
[Authorize(Roles = "PetLover")]
[RoutePrefix("api/pets")]
public class PetController : ApiController
{
// GET api/pet
[Route]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/pet/5
[Route("{id:int}")]
public string Get(int id)
{
return "value";
}
// POST api/pet
[Route]
public void Post([FromBody]string value)
{
}
// PUT api/pet/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/pet/5
public void Delete(int id)
{
}
}
CarController
[RoutePrefix("api/cars")]
public class CarController : ApiController
{
// GET api/car
[AllowAnonymous]
[Route]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/car/5
[Authorize(Roles = "CarOwner")]
[Route("{id:int}")]
public string Get(int id)
{
return "value";
}
// POST api/car
[Authorize(Roles = "CarOwner")]
[Route]
public void Post([FromBody]string value)
{
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Filters.Add(new ApiKeyFilter());
//config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
}
}
到目前爲止好。這裏沒問題。
問:
現在我想的是,「用戶」角色的API生成過程中考慮。我只想顯示用戶可以使用此api_key消耗的文檔中的資源和操作。
輸出應該看起來像(/ swagger/ui/index?API_KEY = XXX):
Admin_api_key:
- 汽車
- GET/API /汽車
- 後/ API /汽車
- 獲得/ API /汽車/ {ID }
- 寵物
- GET/API /寵物
- 後/ API /寵物
- 獲得/ API /寵物/(編號)
- 汽車
CarOwner_api_key:
- 汽車
- get/api/cars
- 後/ API /汽車
- GET/API /汽車/(編號)
- 汽車
PetLover_api_key:
- 汽車
- 獲得/ API /汽車
- 寵物
- GET/API /寵物
- 後/ API /寵物
- 獲得/ API /寵物/(編號)
- 汽車
invalid_api_key:
- 沒什麼可顯示的
在API規範生成期間,我無法訪問HttpRequest以讀取任何查詢字符串或任何頭信息。
我已經有了一個尋找到一個DelegatingHandler,但我有麻煩讀出任何Swashbuckle過濾主要(OperationFilter,DocumentFilter上),我也無法讀出在該主要CustomProvider。
public class CustomAuthenticationMessageHandler : DelegatingHandler
{
private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
private readonly string authenticationScheme = "Bearer";
private readonly string queryStringApiKey = "api_key";
public bool AllowMultiple
{
get { return false; }
}
public CustomAuthenticationMessageHandler()
{
if (allowedApps.Count == 0)
{
allowedApps.Add("PetLover_api_key", new[] {"PetLover"});
allowedApps.Add("CarOwner_api_key", new[] {"CarOwner"});
allowedApps.Add("Admin_api_key", new[] {"PetLover", "CarOwner"});
}
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var req = request;
Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
string rawAuthzHeader = null;
if (queryStrings.ContainsKey(queryStringApiKey))
{
rawAuthzHeader = queryStrings[queryStringApiKey];
}
else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
rawAuthzHeader = req.Headers.Authorization.Parameter;
}
if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
request.GetRequestContext().Principal = currentPrincipal;
}
else
{
}
return await base.SendAsync(request, cancellationToken);
}
}
我發現了一些類似的問題/問題,但沒有真正的答案。
Web API Documentation using swagger
Restrict access to certain API controllers in Swagger using Swashbuckle and ASP.NET Identity
{hxxps://} github.com/domaindrivendev/Swashbuckle/issues/334
{hxxps://} github.com/domaindrivendev/Swashbuckle/issues/735
{hxxps:/ /}github.com/domaindrivendev/Swashbuckle/issues/478