.net core 3.1 Identity Server4 (NSwag Api授权) 电脑版发表于:2021/1/26 17:52 ![](https://img.tnblog.net/arcimg/hb/bc1fb7ecad85426187e0d7d4b22c7c29.png) >#.net core 3.1 Identity Server4 (NSwag Api授权) [TOC] 创建ApiDemo3接口项目 ------------ ![](https://img.tnblog.net/arcimg/hb/50ff50910d2c4a4c8ebf27b01247e874.png) 引入NSwag库 ------------ ```bash Install-Package NSwag.AspNetCore -Version 13.10.1 ``` 修改接口项目 ------------ tn>先修改`launchSettings.json`的地址 ```json { "profiles": { "ApIDemo2": { "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", "applicationUrl": "http://localhost:9001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ``` tn>再在Identity Server4授权服务器的客户端中添加该地址 ```csharp new Client { ClientId = "apidemo2_swagger", ClientName = "Swagger UI for ApIDemo2", ClientSecrets = {new Secret("secret".Sha256())}, AllowedGrantTypes = GrantTypes.Code, // 启动Pkce RequirePkce = true, RequireClientSecret = false, RedirectUris = { "http://localhost:9001/swagger/oauth2-redirect.html", "http://localhost:9200/swagger/oauth2-redirect.html", }, AllowedCorsOrigins = { "http://localhost:9001", "http://localhost:9200" }, AllowedScopes = { "ApiTwo" } }, ``` tn>回到我们API,添加引用,并在`ConfigureServices`添加相关代码。 ```bash Install-Package IdentityServer4.AccessTokenValidation -Version 3.0.1 ``` ```csharp services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:7200"; // 授权服务器地址 //确定自己是哪个资源(资源名称) options.Audience = "ApiTwo"; options.RequireHttpsMetadata = false; // 是否使用https进行通信 //取消验证用户以及验证角色 options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = false, ValidateAudience = false }; }); ``` tn>现在,您可以通过将注册添加到`ConfigureServices`方法中来将`Swagger`文档生成添加到项目中。 ```csharp services.AddOpenApiDocument(options => { options.DocumentName = "v1"; options.Title = "Protected API"; options.Version = "v1"; // 接着我们在下面进行添加代码 }); ``` tn>为了让NSwag了解哪些端点需要访问令牌并将安全范围添加到Swagger文档中,可以使用`AspNetCoreOperationSecurityScopeProcessor`该类自动扫描您的所有控制器和动作`AuthorizationAttributes`。 ```csharp options.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme { Type = OpenApiSecuritySchemeType.OAuth2, Description = "My Authentication", Flow = OpenApiOAuth2Flow.AccessCode, Flows = new OpenApiOAuthFlows() { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = "https://localhost:7200/connect/authorize", TokenUrl = "https://localhost:7200/connect/token", Scopes = new Dictionary<string, string> { {"ApiTwo", "Swagger UI for ApIDemo2"} } }, } }); options.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer")); ``` tn>然后,您可以通过在`Configure`方法中添加以下内容来在管道中启用`Swagger`文档和`UI` : ```csharp app.UseAuthentication(); app.UseAuthorization(); app.UseOpenApi(); app.UseSwaggerUi3(options => { options.OAuth2Client = new OAuth2ClientSettings(); options.OAuth2Client.ClientId = "apidemo2_swagger"; options.OAuth2Client.ClientSecret = "secret"; options.OAuth2Client.AppName = "Demo API - Swagger"; options.OAuth2Client.UsePkceWithAuthorizationCodeGrant = true; }); ``` 访问测试 ------------ ![](https://img.tnblog.net/arcimg/hb/605013f5b12d4aada663febf18ea8e94.png)