如何在 ASP.Net WebAPI 2.0 中通过基于令牌的身份验证使用 Swagger
How to use Swagger in ASP.Net WebAPI 2.0 with token based authentication
我有一个 ASP.Net WebApi,带有基于令牌的身份验证,我想使用 swagger 为这个 RestApi.
创建文档
Api 目前只有两种方法,一种用于请求令牌,即 http://localhost:4040/token
,另一种用于创建通知。返回的不记名令牌发送如下:
using (var client = new HttpClient())
{
// setup client
client.BaseAddress = new Uri("http://localhost:4040");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var serializedNotification = new JavaScriptSerializer().Serialize(notification);
var stringContent = new StringContent(serializedNotification, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/Notification", stringContent);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
有了 swagger,我可以看到 post 通知方法,但是我无法发出请求,因为我没有令牌,而且我不知道如何在 swagger 中执行此操作。
我自己找到了解决方案。我想分享它以防有人遇到同样的问题。解决方案分为两步,第一步是请求令牌,下一步是将令牌添加到 header 请求中。
所以第一步:
自定义前端以启用 post 请求令牌的请求:
添加一个AuthTokenOperation
class启用,继承IDcoumentFilter
接口,实现Apply方法:
public class AuthTokenOperation : IDocumentFilter
{
/// <summary>
/// Apply custom operation.
/// </summary>
/// <param name="swaggerDoc">The swagger document.</param>
/// <param name="schemaRegistry">The schema registry.</param>
/// <param name="apiExplorer">The api explorer.</param>
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth"},
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter>
{
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
},
}
}
});
}
}
并且在SwaggerConfigclass的register方法中,添加这个action
c.DocumentFilter<AuthTokenOperation>();
到扩展方法:
GlobalConfiguration.Configuration.EnableSwagger
在请求中添加授权令牌header:
添加这个操作class:
/// <summary>
/// The class to add the authorization header.
/// </summary>
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the operation filter.
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters != null)
{
operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
description = "access token",
required = false,
type = "string"
});
}
}
}
并且在SwaggerConfigclass的register方法中,添加这个action
c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
到扩展方法:
GlobalConfiguration.Configuration.EnableSwagger
当然在Authorization字段中,你需要添加:
承载 token_string
我只是想在接受的答案中添加一些内容,当 autorest 用于客户端生成时,接受的答案是不完整的,因为它缺少一些属性。
[Fatal]OperationId is required for all operations. Please add it for
'post' operation of '/authenticate' path. Exception: There was an
error during code generation when trying to add a client for the REST
API Generating client code and adding to project failed Adding REST
API client for failed
post = new Operation
{
operationId = "Auth_AccessToken",
tags = new List<string> { "Auth" },
produces = new List<string>
{
"application/json",
"text/json",
"application/xml",
"text/xml"
},
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter>
{
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "client_id",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "client_secret",
required = true,
@in = "formData"
}
},
responses = new Dictionary<string, Response>
{
{"200", new Response{ description = "OK", schema = new Schema{ type = "object"} } }
}
}
您需要添加 operationId 和响应,autorest 才能正常工作。
我有一个 ASP.Net WebApi,带有基于令牌的身份验证,我想使用 swagger 为这个 RestApi.
创建文档Api 目前只有两种方法,一种用于请求令牌,即 http://localhost:4040/token
,另一种用于创建通知。返回的不记名令牌发送如下:
using (var client = new HttpClient())
{
// setup client
client.BaseAddress = new Uri("http://localhost:4040");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var serializedNotification = new JavaScriptSerializer().Serialize(notification);
var stringContent = new StringContent(serializedNotification, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/Notification", stringContent);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
有了 swagger,我可以看到 post 通知方法,但是我无法发出请求,因为我没有令牌,而且我不知道如何在 swagger 中执行此操作。
我自己找到了解决方案。我想分享它以防有人遇到同样的问题。解决方案分为两步,第一步是请求令牌,下一步是将令牌添加到 header 请求中。
所以第一步:
自定义前端以启用 post 请求令牌的请求:
添加一个AuthTokenOperation
class启用,继承IDcoumentFilter
接口,实现Apply方法:
public class AuthTokenOperation : IDocumentFilter
{
/// <summary>
/// Apply custom operation.
/// </summary>
/// <param name="swaggerDoc">The swagger document.</param>
/// <param name="schemaRegistry">The schema registry.</param>
/// <param name="apiExplorer">The api explorer.</param>
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth"},
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter>
{
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
},
}
}
});
}
}
并且在SwaggerConfigclass的register方法中,添加这个action
c.DocumentFilter<AuthTokenOperation>();
到扩展方法:
GlobalConfiguration.Configuration.EnableSwagger
在请求中添加授权令牌header:
添加这个操作class:
/// <summary>
/// The class to add the authorization header.
/// </summary>
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the operation filter.
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters != null)
{
operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
description = "access token",
required = false,
type = "string"
});
}
}
}
并且在SwaggerConfigclass的register方法中,添加这个action
c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
到扩展方法:
GlobalConfiguration.Configuration.EnableSwagger
当然在Authorization字段中,你需要添加: 承载 token_string
我只是想在接受的答案中添加一些内容,当 autorest 用于客户端生成时,接受的答案是不完整的,因为它缺少一些属性。
[Fatal]OperationId is required for all operations. Please add it for 'post' operation of '/authenticate' path. Exception: There was an error during code generation when trying to add a client for the REST API Generating client code and adding to project failed Adding REST API client for failed
post = new Operation
{
operationId = "Auth_AccessToken",
tags = new List<string> { "Auth" },
produces = new List<string>
{
"application/json",
"text/json",
"application/xml",
"text/xml"
},
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter>
{
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "client_id",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "client_secret",
required = true,
@in = "formData"
}
},
responses = new Dictionary<string, Response>
{
{"200", new Response{ description = "OK", schema = new Schema{ type = "object"} } }
}
}
您需要添加 operationId 和响应,autorest 才能正常工作。