增加验证服务

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=398940public 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=="1"? 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("123456".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": "5000","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

转载于:https://www.cnblogs.com/nontracey/p/9967665.html

微服务网关从零搭建——(三)Ocelot网关 + identity4相关推荐

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

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

  2. 从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(三) (mini-cloud) 搭建认证服务(认证/资源分离版) oauth2.0 (中)

    本文承接上文<从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(三) (mini-cloud) 搭建认证服务(认证/资源分离版) oauth2.0 (上)> ...

  3. 【NET CORE微服务一条龙应用】第三章 认证授权与动态权限配置

    [NET CORE微服务一条龙应用]第三章 认证授权与动态权限配置 介绍 系列目录:[NET CORE微服务一条龙应用]开始篇与目录 在微服务的应用中,统一的认证授权是必不可少的组件,本文将介绍微服务 ...

  4. 微服务商城mall-swarm本地搭建

    mall-swarm 微服务商城系统 本地搭建步骤 目录 一.环境搭建: 1.首先从git中下载代码 2.安装检查自己的jdk版本(我之前已经安装好了)​​3.安装Mysql---推荐使用docker ...

  5. 从零开始实现基于go-zero框架的微服务电商项目(三)——gorm、redis、腾讯云SMS、validate、md5加密、日志输入到kafka的添加

    从零开始实现基于go-zero框架的微服务电商项目(三)--gorm.redis.腾讯云SMS.validate.md5加密.日志输入到kafka的添加 项目地址:liuxianloveqiqi/Xi ...

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

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

  7. SpringCloud微服务项目实战 - 2.App登录及网关

    如果你追求一个局部的更好甚至完美,你有可能花费巨大的资源和时间: 从总体上看,这往往意味着总体的浪费和失败,这是传说中的"打赢了战役打输了战争". 系列文章目录 项目搭建 App登 ...

  8. 微服务架构的环境搭建及简单测试

    目录 一.系统架构的演变过程 1.0 前言 1.1 单体应用架构 1.2 垂直应用架构 1.3 分布式架构 1.4 SOA架构 1.5 微服务架构 二.微服务架构搭建 2.1 微服务架构简介 2.2  ...

  9. 杂谈:微服务的体系结构评审的三个问题

    点击蓝色"程序猿DD"关注我 回复"资源"获取独家整理的学习资料! 作者 | 遗失的拂晓 来源 | 公众号「锅外的大佬」 面向微服务的体系结构如今风靡全球.这是 ...

最新文章

  1. 少样本学习原理快速入门,并翻译《Free Lunch for Few-Shot Learning: Distribution Calibration》
  2. ecshop清除mysql缓存_禁用ecshop缓存,关闭ecshop缓存功能
  3. linux nginx大量TIME_WAIT的解决办法--转
  4. marked Options
  5. 20175212童皓桢 Java实验二-面向对象程序设计实验报告
  6. word2vec原理_Word2vec详细整理(1)—权重更新原理
  7. [转]MySQL日志——Undo | Redo
  8. RocketMQ消费幂等性处理
  9. 电脑底部任务栏点不动_15个小技巧,让我的Windows电脑更好用了!
  10. Day7--误差反向传播
  11. 如何在NVIDIA(英伟达)官网下载老版本Toolkit-SDK---例如下载CUDA Toolkit 8.0
  12. mysql acid介绍_InnoDB ACID模型介绍
  13. day6--pandas
  14. Android性能专项FPS测试实践
  15. unity 游戏上架Google Play
  16. 郁金香商业辅助教程 2016 笔记 1~5
  17. bzoj-1488 图的同构
  18. 小车高速怎么收费标准_高速如何计费 2019高速公路收费标准及计算方法
  19. 计算机桌面壁纸怎么保存,电脑桌面背景图片保存路径
  20. leetcode加一

热门文章

  1. JVM是怎么工作的?
  2. javaScript-进阶篇(三)
  3. CSS3 filter:drop-shadow滤镜与box-shadow区别
  4. android系统各个输出log对应层次文件
  5. tomcat7.0 安装启动之后localhost:8080页面进不去,提示错误500
  6. 杭电 1711 Number Sequence 1686 2203
  7. 二维“有序”数组查找问题
  8. windows平台搭建Mongo数据库复制集(类似集群)(三)
  9. 【运营】各大电商七夕活动对比
  10. CSS3 美女动画相框