关于 IdentityServer4 与 ocelot 博客园里已经有很多介绍我这里就不再重复了.
ocelot 与 IdentityServer4 组合认证博客园里也有很多, 但大多使用 ocelot 内置的认证, 而且大多都是用来认证 API 的, 查找了很多资料也没看到如何认证 oidc, 所以这里的 ocelot 实际只是作为统一入口而不参与认证, 认证的完成依然在客户端. 代码是使用 IdentityServer4 的 Quickstart5_HybridAndApi 示例修改的. 项目结构如下
一 ocelot 网关
我们先在示例添加一个网关.
修改 launchSettings.JSON 中的端口为 54660
- "NanoFabricApplication": {
- "commandName": "Project",
- "launchBrowser": true,
- "applicationUrl": "http://localhost:54660",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- }
配置文件如下
- {
- "ReRoutes": [
- { // MvcClient
- "DownstreamPathTemplate": "/MvcClient/{route}",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50891
- }
- ],
- "UpstreamPathTemplate": "/MvcClient/{route}",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- },
- { // signin-oidc
- "DownstreamPathTemplate": "/signin-oidc",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50891
- }
- ],
- "UpstreamPathTemplate": "/signin-oidc",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- },
- { // signout-callback-oidc
- "DownstreamPathTemplate": "/signout-callback-oidc",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50891
- }
- ],
- "UpstreamPathTemplate": "/signout-callback-oidc",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- },
- { // MyApi
- "DownstreamPathTemplate": "/MyApi/{route}",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50890
- }
- ],
- "UpstreamPathTemplate": "/MyApi/{route}",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- },
- { // IdentityServer
- "DownstreamPathTemplate": "/{route}",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50875
- }
- ],
- "UpstreamPathTemplate": "/IdentityServer/{route}",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- },
- { // IdentityServer
- "DownstreamPathTemplate": "/{route}",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 50875
- }
- ],
- "UpstreamPathTemplate": "/{route}",
- "UpstreamHeaderTransform": {
- "X-Forwarded-For": "{RemoteIpAddress}"
- }
- }
- ]
- }
- View Code
这里我们定义 3 个下游服务, MvcClient,MyApi,IdentityServer, 并使用路由特性把 signin-oidc,signout-callback-oidc 导航到 MvcClient, 由 MvcClient 负责生成最后的 Cooike. 并将默认路由指定到 IdentityServer 服务.
在 ConfigureServices 中添加 Ocelot 服务.
- services.AddOcelot()
- .AddCacheManager(x =>
- {
- x.WithDictionaryHandle();
- })
- .AddPolly()
在 Configure 中使用 Ocelot 中间件
App.UseOcelot().Wait();
Ocelot 网关就部署完成了.
二 修改 QuickstartIdentityServer 配置
首先依然是修改 launchSettings.JSON 中的端口为 50875
在 ConfigureServices 中修改 AddIdentityServer 配置中的 PublicOrigin 和 IssuerUri 的 Url 为 http://localhost:54660/IdentityServer/
- services.AddIdentityServer(Option =>
- {
- Option.PublicOrigin = "http://localhost:54660/IdentityServer/";
- Option.IssuerUri = "http://localhost:54660/IdentityServer/";
- })
- .AddDeveloperSigningCredential()
- .AddInMemoryIdentityResources(Config.GetIdentityResources())
- .AddInMemoryApiResources(Config.GetApiResources())
- .AddInMemoryClients(Config.GetClients())
- .AddTestUsers(Config.GetUsers());
这样一来发现文档中的 IdentityServer 地址就变为网关的地址了, 进一步实现 IdentityServer 的负载均衡也是没有问题的.
修改 Config.cs 中 mvc 客户端配置如下
- ClientId = "mvc",
- ClientName = "MVC Client",
- AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
- ClientSecrets =
- {
- new Secret("secret".Sha256())
- },
- // AccessTokenType = AccessTokenType.Reference,
- RequireConsent = true,
- RedirectUris = { "http://localhost:54660/signin-oidc" },
- PostLogoutRedirectUris = { "http://localhost:54660/signout-callback-oidc" },
- AllowedScopes =
- {
- IdentityServerConstants.StandardScopes.OpenId,
- IdentityServerConstants.StandardScopes.Profile,
- "api1"
- },
- AllowOfflineAccess = true,
- // 直接返回客户端需要的 Claims
- AlwaysIncludeUserClaimsInIdToken = true,
主要修改 RedirectUris 和 PostLogoutRedirectUris 为网关地址, 在网关也设置了 signin-oidc 和 signout-callback-oidc 转发请求到 Mvc 客户端.
三 修改 MvcClient
修改 MvcClient 的 launchSettings.JSON 端口为 50891.
修改 MvcClient 的 Authority 地址为 http://localhost:54660/IdentityServer 和默认路由地址 MvcClient/{controller=Home}/{action=index}/{id?}
- JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
- services.AddAuthentication(options =>
- {
- options.DefaultScheme = "Cookies";
- options.DefaultChallengeScheme = "oidc";
- //options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
- })
- .AddCookie("Cookies",options=> {
- options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
- options.SlidingExpiration = true;
- })
- .AddOpenIdConnect("oidc", options =>
- {
- options.SignInScheme = "Cookies";
- options.Authority = "http://localhost:54660/IdentityServer";
- options.RequireHttpsMetadata = false;
- options.ClientId = "mvc";
- options.ClientSecret = "secret";
- options.ResponseType = "code id_token";
- options.SaveTokens = true;
- options.GetClaimsFromUserInfoEndpoint = true;
- options.Scope.Add("api1");
- options.Scope.Add("offline_access");
- });
- View Code
- App.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "MvcClient/{controller=Home}/{action=index}/{id?}");
- });
- View Code
修改 HomeController, 将相关地址修改为网关地址
- public async Task<IActionResult> CallApiUsingClientCredentials()
- {
- var tokenClient = new TokenClient("http://localhost:54660/IdentityServer/connect/token", "mvc", "secret");
- var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
- var client = new HttpClient();
- client.SetBearerToken(tokenResponse.AccessToken);
- var content = await client.GetStringAsync("http://localhost:54660/MyApi/identity");
- ViewBag.JSON = JArray.Parse(content).ToString();
- return View("json");
- }
- public async Task<IActionResult> CallApiUsingUserAccessToken()
- {
- var accessToken = await HttpContext.GetTokenAsync("access_token");
- //OpenIdConnectParameterNames
- var client = new HttpClient();
- client.SetBearerToken(accessToken);
- var content = await client.GetStringAsync("http://localhost:54660/MyApi/identity");
- ViewBag.JSON = JArray.Parse(content).ToString();
- return View("json");
- }
- View Code
四 修改 API 项目
API 项目修改多一点.
将 MvcClient 的 HomeController 和相关视图复制过来, 模拟 MVC 与 API 同时存在的项目.
修改 API 的 launchSettings.JSON 端口为 50890.
修改 Startup
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDataProtection(options => options.ApplicationDiscriminator = "00000").SetApplicationName("00000");
- services.AddMvc();
- JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
- services.AddAuthentication(options =>
- {
- options.DefaultScheme = "Cookies";
- options.DefaultChallengeScheme = "oidc";
- }).AddCookie("Cookies")
- .AddOpenIdConnect("oidc", options =>
- {
- options.SignInScheme = "Cookies";
- options.Authority = "http://localhost:54660/IdentityServer";
- options.RequireHttpsMetadata = false;
- options.ClientId = "mvc";
- options.ClientSecret = "secret";
- options.ResponseType = "code id_token";
- options.SaveTokens = true;
- options.GetClaimsFromUserInfoEndpoint = true;
- options.Scope.Add("api1");
- options.Scope.Add("offline_access");
- })
- .AddIdentityServerAuthentication("Bearer", options =>
- {
- options.Authority = "http://localhost:54660/IdentityServer";
- options.RequireHttpsMetadata = false;
- options.ApiSecret = "secret123";
- options.ApiName = "api1";
- options.SupportedTokens= SupportedTokens.Both;
- });
- services.AddAuthorization(option =>
- {
- // 默认 只写 [Authorize], 表示使用 oidc 进行认证
- option.DefaultPolicy = new AuthorizationPolicyBuilder("oidc").RequireAuthenticatedUser().Build();
- //ApiController 使用这个 [Authorize(Policy = "ApiPolicy")], 使用 jwt 认证方案
- option.AddPolicy("ApiPolicy", policy =>
- {
- policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
- policy.RequireAuthenticatedUser();
- });
- });
- }
- public void Configure(IApplicationBuilder App, IHostingEnvironment env)
- {
- //var options = new ForwardedHeadersOptions
- //{
- // ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
- // ForwardLimit = 1
- //};
- //options.KnownNetworks.Clear();
- //options.KnownProxies.Clear();
- //App.UseForwardedHeaders(options);
- //if (env.IsDevelopment())
- //{
- // App.UseDeveloperExceptionPage();
- //}
- //else
- //{
- // App.UseExceptionHandler("/Home/Error");
- //}
- App.UseAuthentication();
- App.UseStaticFiles();
- App.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "MyApi/{controller=MAccount}/{action=Login}/{id?}");
- });
- }
- }
- View Code
主要添加了 oidc 认证配置和配置验证策略来同时支持 oidc 认证和 Bearer 认证.
修改 IdentityController 中的 [Authorize] 特性为[Authorize(Policy = "ApiPolicy")]
依次使用调试 - 开始执行 (不调试) 并选择项目名称启动 QuickstartIdentityServer,Gateway,MvcClient,API, 启动方式如图
应该可以看到 Gateway 启动后直接显示了 IdentityServer 的默认首页
在浏览器输入 http://localhost:54660/MVCClient/Home/index 进入 MVCClient
样式没加载是因为我们修改了默认路由, 没有影响就不再修改了.
点击 Secure 进入需要授权的页面, 这时候会跳转到登陆页面(才怪
实际上我们会遇到一个错误, 这是因为 ocelot 做网关时下游服务获取到的 Host 实际为 localhost:50891, 而在 IdentityServer 中设置的 RedirectUris 为网关的 54660, 我们可以通过 ocelot 转发 X-Forwarded-Host 头, 并在客户端通过 UseForwardedHeaders 中间件来获取头. 但是 UseForwardedHeaders 中间件为了防止 IP 欺骗攻击需要设置 KnownNetworks 和 KnownProxies 以实现严格匹配. 当然也可以通过清空 KnownNetworks 和 KnownProxies 的默认值来不执行严格匹配, 这样一来就有可能受到攻击. 所以这里我直接使用硬编码的方式设置 Host, 实际使用时应从配置文件获取, 同时修改 MvcClient 和 API 相关代码
- App.Use(async (context, next) =>
- {
- context.Request.Host = HostString.FromUriComponent(new Uri("http://localhost:54660/"));
- await next.Invoke();
- });
- //var options = new ForwardedHeadersOptions
- //{
- // ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
- // ForwardLimit = 1
- //};
- //options.KnownNetworks.Clear();
- //options.KnownProxies.Clear();
- //App.UseForwardedHeaders(options);
在反向代理情况下通过转发 X-Forwarded-Host 头来获取 Host 地址应该时常见设置不知道还有没有其他更好的解决办法.
再次启动 MVCClient 并输入 http://localhost:54660/MvcClient/Home/Secure.
使用 bob,password 登陆一下
点击 Yes, Allow 返回 http://localhost:54660/MvcClient/Home/Secure, 此时可以查看到登陆后的信息
分别点击 Call API using user token 和 Call API using application identity 来验证一下通过 access_token 和 ClientCredent 模式请求来请求 API
成功获取到返回值.
输入 http://localhost:54660/myapi/Home/index 来查看 API 情况
请求成功.
点击 Secure 从 API 项目查看用户信息, 此时展示信息应该和 MvcClient 一致
嗯, 并没有看到用户信息而是又到了授权页....., 这是因为. netCore 使用 DataProtection 来保护数据(点击查看详细信息),API 项目不能解析由 Mvc 生成的 Cookie, 而被重定向到了 IdentityServer 服务中.
在 MvcClient 和 API 的 ConfigureServices 下添加如下代码来同步密钥环.
services.AddDataProtection(options => options.ApplicationDiscriminator = "00000").SetApplicationName("00000");
再次启动 MvcClient 和 API 项目并在浏览器中输入 http://localhost:54660/MvcClient/home/Secure, 此时被要求重新授权, 点击 Yes, Allow 后看到用户信息
再输入 http://localhost:54660/myapi/Home/Secure 从 API 项目查看用户信息
分别点击 Call API using user token 和 Call API using application identity 来验证一下通过 access_token 和 ClientCredent 模式请求来请求 API
请求成功.
如此我们便实现了通过 ocelot 实现统一入口, 通过 IdentityServer4 来实现认证的需求
源代码
参考
- https://www.cnblogs.com/stulzq/category/1060023.html
- https://www.cnblogs.com/xiaoti/p/10118930.html
- https://www.cnblogs.com/jackcao/tag/identityserver4/
来源: https://www.cnblogs.com/nasha/p/10160695.html