增加验证服务

1.创建名为AuthService 的core 空项目

2.修改startup文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConsulRegisterHelper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; namespace AuthService
{
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//注入IdentityServer服务
services.AddIdentityServer()
.AddDeveloperSigningCredential()//开发临时证书
.AddInMemoryClients(ApiConfig.GetClients())
.AddInMemoryApiResources(ApiConfig.GetApiResources())
.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()//添加自定义验证
.AddProfileService<ProfileService>(); ;
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.RegisterConsul(lifetime, new ServiceEntity
{
IP = NetworkHelper.LocalIPAddress,
Port = Convert.ToInt32(Configuration.GetSection("Setting")["Port"]),
ServiceName = Configuration.GetSection("Setting")["ServiceName"],
ConsulIP = Configuration.GetSection("Setting")["ConsulIP"],
ConsulPort = Convert.ToInt32(Configuration.GetSection("Setting")["ConsulPort"])
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("身份验证服务启动成功!");
});
}
}
}

Startup

3.修改Program

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; namespace AuthService
{
public class Program
{
public static string StartPort;
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.Build();
StartPort = config.GetSection("Setting")["Port"];
CreateWebHostBuilder(args).Build().Run();
} public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls($"http://*:{StartPort}")
.UseStartup<Startup>();
}
}

Program

4.增加setting文件节点

"Setting": {
"Port": "7500",
"ServiceName": "authService",
"ConsulIP": "localhost",
"ConsulPort": "8500"
}

5.增加身份验证自定义用户验证相关

using IdentityServer4.Models;
using IdentityServer4.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace AuthService
{
public class ProfileService : IProfileService
{
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var claims = context.Subject.Claims.ToList();
context.IssuedClaims = claims.ToList();
} public async Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
}
}
}

ProfileService.cs

using IdentityServer4.Models;
using IdentityServer4.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks; namespace AuthService
{
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
//ToDo:验证自定义用户
//LoginUser loginUser = null;
bool isAuthenticated = context.UserName=="aaa"&&context.Password==""? true :false; //loginUserService.Authenticate(context.UserName, context.Password, out loginUser);
if (!isAuthenticated)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账户名密码错误");
}
else
{
context.Result = new GrantValidationResult(
subject: context.UserName,
authenticationMethod: "custom",
claims: new Claim[] {
new Claim("Name", context.UserName),
new Claim("Id", ""),
new Claim("RealName", ""),
new Claim("Email", "")
}
);
}
return Task.CompletedTask;
}
}
}

ResourceOwnerPasswordValidator.cs

6.增加示例数据

using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace AuthService
{
/// <summary>
/// 因为此处采用in-memory,所以硬编码一些api,以及client
/// </summary>
public class ApiConfig
{
/// <summary>
/// 定义ApiResource 这里的资源(Resources)指的就是我们的API
/// </summary>
/// <returns>ApiResource枚举</returns>
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
new ApiResource("demoAPi", "测试API"),
};
} /// <summary>
/// 定义受信任的客户端 Client
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "OcelotDemo",//客户端的标识,要是惟一的
ClientSecrets = new [] { new Secret("".Sha256()) },//客户端密码,进行了加密
AllowedGrantTypes = GrantTypes.ClientCredentials,//授权方式,这里采用的是客户端认证模式,只要ClientId,以及ClientSecrets正确即可访问对应的AllowedScopes里面的api资源
AllowedScopes = new [] { "demoAPi"}//定义这个客户端可以访问的APi资源数组
}
};
}
}
}

ApiConfig.cs

改变网关

1.修改Startup.cs

增加节点

 services.AddAuthentication()
.AddIdentityServerAuthentication(Configuration.GetSection("Setting")["AuthScheme"], options => {
options.Authority = Configuration.GetSection("Setting")["AuthUrl"];
options.ApiName = Configuration.GetSection("Setting")["AuthApiName"];
options.SupportedTokens = SupportedTokens.Both;
options.RequireHttpsMetadata = false;
});

ConfigureServices内容

2.修改网关配置

 //添加身份验证
"AuthenticationOptions": {
"AuthenticationProviderKey": "OcelotKey",
"AllowedScopes": [ "demoAPi"]
}

configuration.json

3.修改配置文件appsettings.json

 "Setting": {
"Port": "",
"AuthScheme": "OcelotKey", //需要和ReRoutes中的AuthenticationProviderKey一致
"AuthUrl": "http://192.168.66.241:7500", // 验证服务地址 注意 必须带有http
"AuthApiName": "demoAPi" //和 需要被验证服务的服务名称一致
}

增加节点内容

注:

AuthUrl 中的 http://  必填 不然会出现500异常

AuthApiName  需要验证服务的服务名称一致 即 需要和scopename 一致

注释部分 错误会造成网关转发跳转出错

测试demoAPI无需改动

测试步骤:

1.token获取

post

请求url: http://192.168.66.241:5000/auth/login

参数 :

grant_type:client_credentials
client_id:OcelotDemo
client_secret:123456

如图:

2.测试访问

get

url:192.168.66.241:5000/demo1/values

参数 :

Authorization:Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjRkMDRhNjk4OTZhMGNhYjZiY2Y4MjBiOTgyOTdlMjk2IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NDIzMzMwNzQsImV4cCI6MTU0MjMzNjY3NCwiaXNzIjoiaHR0cDovLzE5Mi4xNjguNjYuMjQxOjc1MDAiLCJhdWQiOlsiaHR0cDovLzE5Mi4xNjguNjYuMjQxOjc1MDAvcmVzb3VyY2VzIiwiZGVtb0FQaSJdLCJjbGllbnRfaWQiOiJPY2Vsb3REZW1vIiwic2NvcGUiOlsiZGVtb0FQaSJdfQ.frqi9W3Yt2XpKStaxLWprVwaer1AB0eeXRdXoGxUBa0IAH-6kzjXKKxznTx-DvEiitZXuF9QBetcbe-otHFG0sHWhQstbD-m8GOHjp8C1RqQ1QFDjO6VspgMEjtugeiOuG2CibStySMZiWl4FpftMsijh9Qzi7RJn6DeHNChLXuv0R2XxCvJa0Bx2hUkRt8yH2pxhrFr4XpxKmtjlks2saPWIrN3D3JWYYcILMcQK-1GDRgc7v-q-KwnCL3DWWdF1kLDeaKv2VgLvnofwfUGQZ2fqZv91t0K0meoWUR3mxPo3JpoO5PnWI0-bttBcoKEC__k3ZgcoKUtPhtgUfcIeA
Content-Type:application/json

如图:

再次引用参考链接:

微服务系列教程

https://www.cnblogs.com/edisonchou/p/dotnetcore_microservice_foundation_blogs_index_final.html

微服务网关从零搭建——(三)Ocelot网关 + identity4的更多相关文章

  1. 庐山真面目之六微服务架构Consul集群、Ocelot网关集群和Nginx版本实现

    庐山真面目之六微服务架构Consul集群.Ocelot网关集群和Nginx版本实现 一.简介      在上一篇文章<庐山真面目之五微服务架构Consul集群.Ocelot网关和Nginx版本实 ...

  2. 庐山真面目之七微服务架构Consul集群、Ocelot网关集群和IdentityServer4版本实现

    庐山真面目之七微服务架构Consul集群.Ocelot网关集群和IdentityServer4版本实现 一.简介      在上一篇文章<庐山真面目之六微服务架构Consul集群.Ocelot网 ...

  3. 微服务之:从零搭建ocelot网关和consul集群

    介绍 微服务中有关键的几项技术,其中网关和服务服务发现,服务注册相辅相成. 首先解释几个本次教程中需要的术语 网关 Gateway(API GW / API 网关),顾名思义,是企业 IT 在系统边界 ...

  4. 微服务之十四如何在 Ocelot 网关中配置多实例 Swagger 访问

    一.介绍 当我们开发基于微服务的应用程序的时候,有一个环节总是跳不过去的,那就是要创建 WebApi,然后,我们的应用程序基于 WebApi 接口去访问.在没有 Swagger 以前,我们开发好了 W ...

  5. 庐山真面目之十二微服务架构基于Docker搭建Consul集群、Ocelot网关集群和IdentityServer版本实现

    庐山真面目之十二微服务架构基于Docker搭建Consul集群.Ocelot网关集群和IdentityServer版本实现 一.简介      在第七篇文章<庐山真面目之七微服务架构Consul ...

  6. 微服务指南走北(三):Restful API 设计简述

    API的定义取决于选择的IPC通信方式,假设是消息机制(如 AMQP 或者 STOMP).API则由消息频道(channel)和消息类型.假设是使用HTTP机制,则是基于请求/响应(调用http的ur ...

  7. 微服务网关从零搭建——(八)Ocelot网关中加入skywalking APM

    准备工作 一.下载skywalking 本例使用的是 注: 1.解压后执行完2,3步骤后运行\bin\startup.bat 2.默认后台端口为8080 如需修改则修改\webapp\webapp.y ...

  8. 微服务网关从零搭建——(一)创建测试api以及api自动注入consul

    本系列编写目的纯属个人开发记录  以下代码均为demo级 如有需要 请自行优化 代码完整包由于公司电脑加密 无法上传整包的demo文件 consul 开发环境简易处理 consul 下载地址 : ht ...

  9. 微服务网关从零搭建——(七)更改存储方式为oracle

    资源准备: 下载开源项目 新建oracle表: -- ---------------------------- -- Table structure for OcelotGlobalConfigura ...

随机推荐

  1. web 开发之js---js获取select标签选中的值

    var obj = document.getElementByIdx_x(”testSelect”); //定位id var index = obj.selectedIndex; // 选中索引 va ...

  2. convex hull

    1 什么是convex hull 就是凸包,是计算几何中的一个概念,计算几何是计算机图形学的基础之一. 对于二维平面来说是这样的:对于二维平面上的点集,凸包是位于最外层的点构成的包围其它所有的点的凸多 ...

  3. Ubuntu下Zabbix服务器监控工具部署

    Ubuntu下Zabbix服务器监控工具部署 一 安装安装Apache.Mysql.Php.zabbix sudo apt-get update sudo apt-get install apache ...

  4. ubuntu将mysql、nginx添加到环境变量中

    vim /etc/profile 添加 export PATH="$PATH:/usr/local/mysql/bin" export PATH="$PATH:/usr/ ...

  5. USACO 刷题有感

    最近每天都尽量保持着每天一道USACO的题目,呵呵,一开始都是满简单的,一看题目基本上思路就哗啦啦地出来了,只不过代码实现有点麻烦,花了一些时间去调试,总体感觉还不错,但是越往后做,应该就很难保持一天 ...

  6. 【T^T】【周赛】第一周周赛——欢迎16级的新同学

    借光光,YZC的福气(今天拿到Rank1),本来还可以更好的,前面吃M去了,ABC都很晚切,而且异常兴奋,结果WA了好多发,但还是由于水题看题不清,分析不清导致的 A Home W的数学 Descri ...

  7. Glide 图片形状裁剪 ,滤镜等

    Glide . Picasso . Fresco 已逐渐成为Android主流的图片加载工具(个人见解,使用Volley.ImageLoader.xUtils的大佬们请勿喷~),在多数Android程 ...

  8. P2570 [ZJOI2010]贪吃的老鼠

    传送门 →_→唯一一篇能看得懂的题解---->这里 很容易想到二分+网络流,然而并没有什么卵用--出题人的思路太神了-- 首先考虑如果一块奶酪在同一时间可以被多只老鼠吃的话,该如何建图.首先不难 ...

  9. magento Grid 显示下拉菜单属性

    在使用grid时自己新建了几个属性,然后其中有一个是下拉单,即deal_status protected function _prepareCollection() { $collection = M ...

  10. python批量删除文件夹

    制作的python程序跑一次就占200多内存在temp下面,关键是还不释放,最开始都没有发现这个问题,知道自己的c盘越来越小才发现问题所在.所以就有了去删除temp下生成的文件 代码如下: impor ...