添加引用
Swashbuckle.AspNetCore
IdentityServer4.AccessTokenValidationgit
預先準備好IdentityServer4配置client與Api Resources
Startup 配置 Authentication Api Resources 和SwaggerUI Client配置github
public void ConfigureServices(IServiceCollection services) { services.AddMvc(option => { option.Filters.Add(typeof(ActionFilter)); option.Filters.Add(typeof(ExceptionFilter)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); string youAuthority = "http://127.0.0.1"; services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = youAuthority; options.ApiName = "Api"; options.RequireHttpsMetadata = false; }); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "Test Service API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.CustomSchemaIds(type => type.FullName); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{youAuthority}/connect/authorize", TokenUrl = $"{youAuthority}/connect/token", Scopes = new Dictionary<string, string>() { { "scope", "定義的scope" } //Api Resources 中的 scope } }); options.OperationFilter<AuthResponsesOperationFilter>(); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseMiddleware<FirstMiddleware>(); app.UseMvc(); app.UseSwagger(). UseSwaggerUI(options =>![](https://img2018.cnblogs.com/blog/355798/201903/355798-20190328201652364-1689226610.png) { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Test Service API"); //支持 implicit 的 Client options.OAuthClientId("swaggerui"); options.OAuthAppName("Test Service Swagger Ui"); }); }
對有鑑權屬性的方法添加請求時傳遞token和添加預設返回狀態sql
public class AuthResponsesOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { // 反射Controller 包含 AuthorizeAttribute 時在請求頭添加authorization: Bearer var controllerScopes = context.ApiDescription.ControllerAttributes() .OfType<AuthorizeAttribute>() .Select(attr => attr.Policy); var actionScopes = context.MethodInfo .GetCustomAttributes(true) .OfType<AuthorizeAttribute>() .Select(attr => attr.Policy) .Distinct(); var requiredScopes = controllerScopes.Union(actionScopes).Distinct(); if (requiredScopes.Any()) { operation.Responses.Add("401", new Response { Description = "Unauthorized" }); operation.Responses.Add("403", new Response { Description = "Forbidden" }); operation.Security = new List<IDictionary<string, IEnumerable<string>>>(); operation.Security.Add(new Dictionary<string, IEnumerable<string>> { { "oauth2", requiredScopes } }); } } }
在 Action 上添加 Authorizejson
[HttpGet("{id}")] [Authorize] public ActionResult<string> Get(int id) { return "value"; }
效果圖c#
//新增的兩種返回狀態 operation.Responses.Add("401", new Response { Description = "Unauthorized" }); operation.Responses.Add("403", new Response { Description = "Forbidden" });
登陸完後請求會帶上authorization: Bearerapp