前言 建立Web Api项目
在同一个解决方案下建立一个Web Api项目IdentityServer4.WebApi,然后修改Web Api的launchSettings.json。参考第一节,当然可以不修改的,端口号为5001。
{ "profiles": { "IdentityServer4.WebApi": { "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", "applicationUrl": "http://localhost:5001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } 添加Swagger帮助页面官方文档:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio&view=aspnetcore-3.1
在Startup.ConfigureServices方法中将Swagger生成器添加到服务集合:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); }OpenApiInfo需要 using Microsoft.OpenApi.Models;
在该Startup.Configure方法中,启用用于提供生成的JSON文档和Swagger UI的中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }把Web Api设为启动项目,打开::5001/swagger/index.html访问Swagger帮助页面:
如果要在应用程序的根目录(:<port>/)提供Swagger UI ,请将RoutePrefix属性设置为空字符串:
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; });顺便我们把launchSettings.json的"launchUrl": "weatherforecast",删掉,这个是在浏览器中启动的默认URL。然后我们再次启动,就可以直接看到Swagger的帮助页面了。
添加库IdentityServer4.AccessTokenValidationWeb Api配置Identity Server就需要对token进行验证, 这个库就是对access token进行验证的. 通过NuGet安装:
在Startup的ConfigureServices里面注册配置:
官方文档的配置:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:5001"; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; }); }官方文档的这个配置是不进行验证Api的Scope和其他一些配置的,也就是只要我拿到Access Token就可以访问了。但实际情况应该是我们可能存在多个api项目,有些只能访问api1、有些只能访问api2。
我们的配置,完整的Web Api Startup.cs
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; namespace IdentityServer4.WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.Authority = "http://localhost:5000"; options.Audience = "api1"; }); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //身份验证 app.UseAuthentication(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; }); app.UseRouting(); //授权 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }AddAuthentication:将身份验证服务添加到DI并配置Bearer为默认方案。
UseAuthentication 将身份验证中间件添加到管道中,以便对主机的每次调用都将自动执行身份验证。
UseAuthorization 添加了授权中间件,以确保匿名客户端无法访问我们的API端点。
添加[Authorize]属性:打开WeatherForecastController, 在Controller上面添加这个属性: