修改接口项目

  在上次的项目基础上,分别修改两个api项目的startup.cs

  

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. var audienceConfig = Configuration.GetSection("Audience");
  4. var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"]));
  5. var tokenValidationParameters = new TokenValidationParameters
  6. {
  7. ValidateIssuerSigningKey = true,
  8. IssuerSigningKey = signingKey,
  9. ValidateIssuer = true,
  10. ValidIssuer = audienceConfig["Iss"],
  11. ValidateAudience = true,
  12. ValidAudience = audienceConfig["Aud"],
  13. ValidateLifetime = true,
  14. ClockSkew = TimeSpan.Zero,
  15. RequireExpirationTime = true,
  16. };
  17. services.AddAuthentication(o =>
  18. {
  19. o.DefaultAuthenticateScheme = "TestKey";
  20. })
  21. .AddJwtBearer("TestKey", x =>
  22. {
  23. x.RequireHttpsMetadata = false;
  24. x.TokenValidationParameters = tokenValidationParameters;
  25. });
  26.  
  27. //services.AddConsulConfig(Configuration);
  28. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  29. }

  修改配置文件

  

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Warning"
  5. }
  6. },
  7. "AllowedHosts": "*",
  8. //"Consul": {
  9. // "Host": "http://192.168.2.29:8500"
  10. //},
  11.  
  12. "Service": {
  13. "Name": "ApiService",
  14. "IP": "192.168.2.16",
  15. "Port": ""
  16. },
  17. "Consul": {
  18. "IP": "192.168.2.29",
  19. "Port": ""
  20. },
  21. "Audience": {
  22. "Secret": "Y2F0Y2hlciUyMHdvbmclMjBsb3ZlJTIwLm5ldA==",
  23. "Iss": "http://www.c-sharpcorner.com/members/catcher-wong",
  24. "Aud": "Catcher Wong"
  25. }
  26. }

  在接口的action中加入[Authorize]属性

  

  1. [Authorize]
  2. [HttpGet]
  3. public string Count()
  4. {
  5. return $"Count {++_count} from ApiServices1";
  6. }

加入Identity

  新建webapi项目 。将authapi项目也加入到consul中。所以要新建health控制器,新建一个授权控制器,修改startup.cs

  

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Mvc;
  7.  
  8. namespace Test.WebApi.AuthServer.Controllers
  9. {
  10. [Produces("application/json")]
  11. [Route("api/[controller]")]
  12. [ApiController]
  13. public class HealthController : ControllerBase
  14. {
  15.  
  16. [HttpGet]
  17. public IActionResult Get() => Ok("ok");
  18. }
  19. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.Extensions.Options;
  11. using Microsoft.IdentityModel.Tokens;
  12.  
  13. namespace Test.WebApi.AuthServer.Controllers
  14. {
  15. [Route("authapi/[controller]")]
  16. [ApiController]
  17. public class AuthController : ControllerBase
  18. {
  19. private IOptions<Audience> _settings;
  20.  
  21. public AuthController(IOptions<Audience> settings)
  22. {
  23. this._settings = settings;
  24. }
  25.  
  26. [HttpGet]
  27. public ActionResult Get(string name, string pwd)
  28. {
  29. //just hard code here.
  30. if (name == "catcher" && pwd == "")
  31. {
  32. var now = DateTime.UtcNow;
  33.  
  34. var claims = new Claim[]
  35. {
  36. new Claim(JwtRegisteredClaimNames.Sub, name),
  37. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  38. new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
  39. };
  40.  
  41. var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.Secret));
  42. var tokenValidationParameters = new TokenValidationParameters
  43. {
  44. ValidateIssuerSigningKey = true,
  45. IssuerSigningKey = signingKey,
  46. ValidateIssuer = true,
  47. ValidIssuer = _settings.Value.Iss,
  48. ValidateAudience = true,
  49. ValidAudience = _settings.Value.Aud,
  50. ValidateLifetime = true,
  51. ClockSkew = TimeSpan.Zero,
  52. RequireExpirationTime = true,
  53.  
  54. };
  55.  
  56. var jwt = new JwtSecurityToken(
  57. issuer: _settings.Value.Iss,
  58. audience: _settings.Value.Aud,
  59. claims: claims,
  60. notBefore: now,
  61. expires: now.Add(TimeSpan.FromMinutes()),
  62. signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
  63. );
  64. var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
  65. var responseJson = new
  66. {
  67. access_token = encodedJwt,
  68. expires_in = (int)TimeSpan.FromMinutes().TotalSeconds
  69. };
  70.  
  71. return new JsonResult(responseJson);
  72. }
  73. else
  74. {
  75. return new JsonResult("");
  76. }
  77. }
  78. }
  79.  
  80. public class Audience
  81. {
  82. public string Secret { get; set; }
  83. public string Iss { get; set; }
  84. public string Aud { get; set; }
  85. }
  86. }

修改 startup.cs

  1. // This method gets called by the runtime. Use this method to add services to the container.
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  5. services.AddOptions();
  6. services.Configure<Controllers.Audience>(Configuration.GetSection("Audience"));
  7. }
  8.  
  9. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  10. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
  11. {
  12. if (env.IsDevelopment())
  13. {
  14. app.UseDeveloperExceptionPage();
  15. }
  16. else
  17. {
  18. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  19. app.UseHsts();
  20. }
  21.  
  22. ConsulService consulService = new ConsulService()
  23. {
  24. IP = Configuration["Consul:IP"],
  25. Port = Convert.ToInt32(Configuration["Consul:Port"])
  26. };
  27. HealthService healthService = new HealthService()
  28. {
  29. IP = Configuration["Service:IP"],
  30. Port = Convert.ToInt32(Configuration["Service:Port"]),
  31. Name = Configuration["Service:Name"],
  32. };
  33. app.RegisterConsul(lifetime, healthService, consulService);
  34.  
  35. app.UseHttpsRedirection();
  36. app.UseMvc();
  37. }

配置文件

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Warning"
  5. }
  6. },
  7. "AllowedHosts": "*",
  8.  
  9. "Service": {
  10. "Name": "AuthService",
  11. "IP": "192.168.2.16",
  12. "Port": ""
  13. },
  14. "Consul": {
  15. "IP": "192.168.2.29",
  16. "Port": ""
  17. },
  18. "Audience": {
  19. "Secret": "Y2F0Y2hlciUyMHdvbmclMjBsb3ZlJTIwLm5ldA==",
  20. "Iss": "http://www.c-sharpcorner.com/members/catcher-wong",
  21. "Aud": "Catcher Wong"
  22. }
  23. }

发布后,部署到IIS中,端口9003

参考链接:

https://www.cnblogs.com/xlxr45/p/11321134.html

修改网关项目

配置文件configuration.json

  1. {
  2. "ReRoutes": [
  3. {
  4. "UseServiceDiscovery": true,
  5. "DownstreamPathTemplate": "/api/{url}",
  6. "DownstreamScheme": "http",
  7. "ServiceName": "ApiService",
  8. "LoadBalancerOptions": {
  9. "Type": "RoundRobin"
  10. },
  11. "UpstreamPathTemplate": "/api/{url}",
  12. "UpstreamHttpMethod": [ "Get" ],
  13. "ReRoutesCaseSensitive": false
  14. },
  15. {
  16. "UseServiceDiscovery": true,
  17. "DownstreamPathTemplate": "/authapi/{url}",
  18. "DownstreamScheme": "http",
  19. "ServiceName": "AuthService",
  20. "LoadBalancerOptions": {
  21. "Type": "RoundRobin"
  22. },
  23. "UpstreamPathTemplate": "/authapi/{url}",
  24. "UpstreamHttpMethod": [ "Get" ],
  25. "ReRoutesCaseSensitive": false
  26. }
  27. ],
  28. "GlobalConfiguration": {
  29. "ServiceDiscoveryProvider": {
  30. "Host": "192.168.2.29",
  31. "Port": ,
  32. "Type": "PollConsul",
  33. "PollingInterval":
  34. }
  35. }
  36. }

运行效果

新建一个cmd项目,测试下

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. HttpClient client = new HttpClient();
  6.  
  7. client.DefaultRequestHeaders.Clear();
  8. client.BaseAddress = new Uri("http://localhost:9000");
  9.  
  10. // 1. without access_token will not access the service
  11. // and return 401 .
  12. var resWithoutToken = client.GetAsync("/api/Counter/Count").Result;
  13.  
  14. Console.WriteLine($"Sending Request to /api/Counter/Count , without token.");
  15. Console.WriteLine($"Result : {resWithoutToken.StatusCode}");
  16.  
  17. //2. with access_token will access the service
  18. // and return result.
  19. client.DefaultRequestHeaders.Clear();
  20. Console.WriteLine("\nBegin Auth....");
  21. var jwt = GetJwt();
  22. Console.WriteLine("End Auth....");
  23. Console.WriteLine($"\nToken={jwt}");
  24.  
  25. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwt}");
  26. var resWithToken = client.GetAsync("/api/Counter/Count").Result;
  27.  
  28. Console.WriteLine($"\nSend Request to /api/Counter/Count , with token.");
  29. Console.WriteLine($"Result : {resWithToken.StatusCode}");
  30. Console.WriteLine(resWithToken.Content.ReadAsStringAsync().Result);
  31.  
  32. //3. visit no auth service
  33. Console.WriteLine("\nNo Auth Service Here ");
  34. client.DefaultRequestHeaders.Clear();
  35. var res = client.GetAsync("/api/Counter/Count").Result;
  36.  
  37. Console.WriteLine($"Send Request to /api/Counter/Count");
  38. Console.WriteLine($"Result : {res.StatusCode}");
  39. Console.WriteLine(res.Content.ReadAsStringAsync().Result);
  40.  
  41. Console.Read();
  42. }
  43.  
  44. private static string GetJwt()
  45. {
  46. HttpClient client = new HttpClient();
  47.  
  48. client.BaseAddress = new Uri( "http://localhost:9000");
  49. client.DefaultRequestHeaders.Clear();
  50.  
  51. var res2 = client.GetAsync("/authapi/auth?name=catcher&pwd=123").Result;
  52.  
  53. dynamic jwt = JsonConvert.DeserializeObject(res2.Content.ReadAsStringAsync().Result);
  54.  
  55. return jwt.access_token;
  56. }
  57. }

postman测试下。

先获取access_token

将access_token放到header中

如果不加入header中,则会报500错误

04 .NET CORE 2.2 使用OCELOT -- identity认证授权的更多相关文章

  1. (10)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Ocelot+Identity Server

    用 JWT 机制实现验证的原理如下图:  认证服务器负责颁发 Token(相当于 JWT 值)和校验 Token 的合法性. 一. 相关概念 API 资源(API Resource):微博服务器接口. ...

  2. ocelot 自定义认证和授权

    ocelot 自定义认证和授权 Intro 最近又重新启动了网关项目,服务越来越多,每个服务都有一个地址,这无论是对于前端还是后端开发调试都是比较麻烦的,前端需要定义很多 baseUrl,而后端需要没 ...

  3. .net core gRPC与IdentityServer4集成认证授权

    前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...

  4. .net core使用Ocelot+Identity Server统一网关验证

    源码下载地址:下载 项目结构如下图: 在Identity Server授权中,实现IResourceOwnerPasswordValidator接口: public class IdentityVal ...

  5. asp.net core网关Ocelot的简单介绍& Ocelot集成Identity认证

    文章简介  Ocelot网关简介 Ocelot集成Idnetity认证处理 Ocelot网关简介 Ocelot是一个基于netcore实现的API网关,本质是一组按特定顺序排列的中间件.Ocelot内 ...

  6. (8)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Ocelot网关(Api GateWay)

    说到现在现有微服务的几点不足: 1) 对于在微服务体系中.和 Consul 通讯的微服务来讲,使用服务名即可访问.但是对于手 机.web 端等外部访问者仍然需要和 N 多服务器交互,需要记忆他们的服务 ...

  7. ASP.NET Core Web API 索引 (更新Identity Server 4 视频教程)

    GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...

  8. ASP.NET Core 2.1 Web API + Identity Server 4 + Angular 6 + Angular Material 实战小项目视频

    视频简介 ASP.NET Core Web API + Angular 6的教学视频 我是后端开发人员, 前端的Angular部分讲的比较差一些, 可以直接看代码!!!! 这是一个小项目的实战视频, ...

  9. net core 2.0 web api + Identity Server 4 + angular 5

    net core 2.0 web api + Identity Server 4 + angular 5前台使用angular 5, 后台是asp.net core 2.0 web api + ide ...

随机推荐

  1. CRT&EXCRT学习笔记

    非扩展 用于求解线性同余方程组 ,其中模数两两互质 . 先来看一看两个显然的定理: 1.若 x \(\equiv\) 0 (mod p) 且 y \(\equiv\) 0 (mod p) ,则有 x+ ...

  2. [原创]Appium与Appium desktop的区别

    1.两者都属于Appium 服务端 2.二者最新版本如下:地址:https://github.com/appium/appium-desktop/releases Appium 服务端支持的:地址:h ...

  3. django rest framework 过滤 lim分页

    一.过滤 1.首先引用diango 自带的过滤配置 2.导入模块 from django_filters.rest_framework import DjangoFilterBackend from ...

  4. 201871010114-李岩松《面向对象程序设计(java)》第十三周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  5. 201871010131-张兴盼《面向对象程序设计(java)》第八周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  6. 【Spark】

    spark-submit --class "org.apache.spark.examples.sql.JavaSparkSQLExample" --master local co ...

  7. 创建maven父子项目(九)

    一.父子-聚合项目 通过 maven 可以创建父子-聚合项目. 所谓的父子项目,即有一个父项目,有多个子项目.这些子项目,在业务逻辑上,都归纳在这个父项目下,并且一般来说,都会有重复的jar包共享.所 ...

  8. CF1234A Equalize Prices

    洛谷 CF1234A Equalize Prices Again 洛谷传送门 题目描述 You are both a shop keeper and a shop assistant at a sma ...

  9. 20191003 「HZOJ NOIP2019 Round #8」20191003模拟

    综述 试题为常州集训2019SCDay2 得分\(100+30(0)+28\) 时之终结 问题描述 HZOJ1310 题解 构造题. 发现部分分有一档是 \(Y\) 是 \(2^x\) ,于是自然想到 ...

  10. .NET三种异步模式(APM、EAP、TAP)

    APM模式: .net 1.0时期就提出的一种异步模式,并且基于IAsyncResult接口实现BeginXXX和EndXXX类似的方法. .net中有很多类实现了该模式(比如HttpWebReque ...