在 ASP.NET WebAPI 集成 Swagger 後,因爲接口使用了 IdentityServer 作的認證,調試起來很不方便;看了下 Swashbuckle 的文檔 ,是支持 OAuth2.0 的配置的,使用的簡化模式(Implicit grant type),交互的流程以下:html
參數:git
GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com
認證服務器迴應客戶端的URI,包含如下參數:github
HTTP/1.1 302 Found
web
Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA
&state=xyz&token_type=example&expires_in=3600
Idrv 中配置客戶端(Client)
api
new Client { ClientName = "Test_API_Flow", ClientId = "api_test_api_flow", Flow = Flows.Implicit, ClientUri = "https://identityserver.io", RequireConsent = true, AllowRememberConsent = true, RedirectUris = new List<string> { "http://localhost:39106/swagger/ui/o2c-html", }, AllowedCorsOrigins = new List<string> { "http://localhost:39106" }, AccessTokenLifetime = 3600, AccessTokenType = AccessTokenType.Jwt, AllowAccessToAllScopes=true },
API:服務器
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority = IdsvSetting.Authority, ValidationMode = ValidationMode.ValidationEndpoint, RequiredScopes=new List<string> {"all","user","order"}} });
/// <summary> /// 早餐控制器 /// </summary> [RoutePrefix("api/v1/breakfast")] public class BreakfastController : ApiController { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); /// <summary> /// 早餐服務 /// </summary> private readonly IBreakfastService _breakfastService; /// <summary> /// 構造方法 /// </summary> /// <param name="breakfastService">早餐服務</param> public BreakfastController(IBreakfastService breakfastService) { _breakfastService = breakfastService; } #region 得到酒店關聯的餐廳的酒店 /// <summary> /// 得到酒店關聯的餐廳的酒店 /// </summary> /// <param name="hotelcd">酒店編號</param> /// <returns>得到酒店關聯的餐廳的酒店</returns> [Authorize] [HttpGet] [Route("{hotelcd}/mapping")] public async Task<IHttpActionResult> GetXhotelBreakfastHotelMappingRequest(string hotelcd) { var response = await _breakfastService.GetXhotelBreakfastHotelMappingRequest(hotelcd); return Json(response); } #endregion } }
配置 SwaggerConfigapp
//https://tsso.xxx.cn/connect/authorize?response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A39106%2Fswagger%2Fui%2Fo2c-html&realm=test-realm&client_id=api_test_api_flow&scope=all%20%20&state=oauth2 c.OAuth2("oauth2") .Description("OAuth2 Implicit Grant") .Flow("implicit") .AuthorizationUrl("https://tsso.xxx.cn/connect/authorize") //.TokenUrl("https://sso.xxx.cn/connect/token") .Scopes(scopes => { scopes.Add("all", "all access to protected resources"); scopes.Add("user", "user access to protected resources"); scopes.Add("order", "order access to protected resources"); }); ...
c.OperationFilter<AssignOAuth2SecurityRequirements>(); c.EnableOAuth2Support( clientId: "api_test_api_flow", clientSecret: null, realm: "test-realm", appName: "Swagger UI" //additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } } );
public class AssignOAuth2SecurityRequirements : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline(); var allowsAnonymous = actFilters.Select(f => f.Instance).OfType<OverrideAuthorizationAttribute>().Any(); if (allowsAnonymous) return; // must be an anonymous method //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline() // .Select(filterInfo => filterInfo.Instance) // .OfType<AllowAnonymousAttribute>() // .SelectMany(attr => attr.Roles.Split(',')) // .Distinct(); if (operation.security == null) operation.security = new List<IDictionary<string, IEnumerable<string>>>(); var oAuthRequirements = new Dictionary<string, IEnumerable<string>> { {"oauth2", new List<string> {"all","user","order"}} }; operation.security.Add(oAuthRequirements); } }
OK ,配置完成,點擊紅色的圈圈,登陸成功會302到 http://localhost:39106/swagger/ui/o2c-htm 上dom
固然也能夠退出受權:async
REFER:ide
https://www.scottbrady91.com/Identity-Server/ASPNET-Core-Swagger-UI-Authorization-using-IdentityServer4
https://stackoverflow.com/questions/33752900/enable-oauth2-client-credentials-flow-in-swashbuckle
https://stackoverflow.com/questions/29275499/swagger-swashbuckle-oauth2-with-resource-owner-password-credentials-grant?rq=1
http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2/