修改接口项目

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

  

 public void ConfigureServices(IServiceCollection services)
{
var audienceConfig = Configuration.GetSection("Audience");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(audienceConfig["Secret"]));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Iss"],
ValidateAudience = true,
ValidAudience = audienceConfig["Aud"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = "TestKey";
})
.AddJwtBearer("TestKey", x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = tokenValidationParameters;
}); //services.AddConsulConfig(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

  修改配置文件

  

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
//"Consul": {
// "Host": "http://192.168.2.29:8500"
//}, "Service": {
"Name": "ApiService",
"IP": "192.168.2.16",
"Port": ""
},
"Consul": {
"IP": "192.168.2.29",
"Port": ""
},
"Audience": {
"Secret": "Y2F0Y2hlciUyMHdvbmclMjBsb3ZlJTIwLm5ldA==",
"Iss": "http://www.c-sharpcorner.com/members/catcher-wong",
"Aud": "Catcher Wong"
}
}

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

  

[Authorize]
[HttpGet]
public string Count()
{
return $"Count {++_count} from ApiServices1";
}

加入Identity

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

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; namespace Test.WebApi.AuthServer.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class HealthController : ControllerBase
{ [HttpGet]
public IActionResult Get() => Ok("ok");
}
}
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; namespace Test.WebApi.AuthServer.Controllers
{
[Route("authapi/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private IOptions<Audience> _settings; public AuthController(IOptions<Audience> settings)
{
this._settings = settings;
} [HttpGet]
public ActionResult Get(string name, string pwd)
{
//just hard code here.
if (name == "catcher" && pwd == "")
{
var now = DateTime.UtcNow; var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, name),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
}; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.Secret));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = _settings.Value.Iss,
ValidateAudience = true,
ValidAudience = _settings.Value.Aud,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true, }; var jwt = new JwtSecurityToken(
issuer: _settings.Value.Iss,
audience: _settings.Value.Aud,
claims: claims,
notBefore: now,
expires: now.Add(TimeSpan.FromMinutes()),
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var responseJson = new
{
access_token = encodedJwt,
expires_in = (int)TimeSpan.FromMinutes().TotalSeconds
}; return new JsonResult(responseJson);
}
else
{
return new JsonResult("");
}
}
} public class Audience
{
public string Secret { get; set; }
public string Iss { get; set; }
public string Aud { get; set; }
}
}

修改 startup.cs

  // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
services.Configure<Controllers.Audience>(Configuration.GetSection("Audience"));
} // 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();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
} ConsulService consulService = new ConsulService()
{
IP = Configuration["Consul:IP"],
Port = Convert.ToInt32(Configuration["Consul:Port"])
};
HealthService healthService = new HealthService()
{
IP = Configuration["Service:IP"],
Port = Convert.ToInt32(Configuration["Service:Port"]),
Name = Configuration["Service:Name"],
};
app.RegisterConsul(lifetime, healthService, consulService); app.UseHttpsRedirection();
app.UseMvc();
}

配置文件

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*", "Service": {
"Name": "AuthService",
"IP": "192.168.2.16",
"Port": ""
},
"Consul": {
"IP": "192.168.2.29",
"Port": ""
},
"Audience": {
"Secret": "Y2F0Y2hlciUyMHdvbmclMjBsb3ZlJTIwLm5ldA==",
"Iss": "http://www.c-sharpcorner.com/members/catcher-wong",
"Aud": "Catcher Wong"
}
}

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

参考链接:

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

修改网关项目

配置文件configuration.json

{
"ReRoutes": [
{
"UseServiceDiscovery": true,
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"ServiceName": "ApiService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UpstreamPathTemplate": "/api/{url}",
"UpstreamHttpMethod": [ "Get" ],
"ReRoutesCaseSensitive": false
},
{
"UseServiceDiscovery": true,
"DownstreamPathTemplate": "/authapi/{url}",
"DownstreamScheme": "http",
"ServiceName": "AuthService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UpstreamPathTemplate": "/authapi/{url}",
"UpstreamHttpMethod": [ "Get" ],
"ReRoutesCaseSensitive": false
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "192.168.2.29",
"Port": ,
"Type": "PollConsul",
"PollingInterval":
}
}
}

运行效果

新建一个cmd项目,测试下

class Program
{
static void Main(string[] args)
{
HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Clear();
client.BaseAddress = new Uri("http://localhost:9000"); // 1. without access_token will not access the service
// and return 401 .
var resWithoutToken = client.GetAsync("/api/Counter/Count").Result; Console.WriteLine($"Sending Request to /api/Counter/Count , without token.");
Console.WriteLine($"Result : {resWithoutToken.StatusCode}"); //2. with access_token will access the service
// and return result.
client.DefaultRequestHeaders.Clear();
Console.WriteLine("\nBegin Auth....");
var jwt = GetJwt();
Console.WriteLine("End Auth....");
Console.WriteLine($"\nToken={jwt}"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwt}");
var resWithToken = client.GetAsync("/api/Counter/Count").Result; Console.WriteLine($"\nSend Request to /api/Counter/Count , with token.");
Console.WriteLine($"Result : {resWithToken.StatusCode}");
Console.WriteLine(resWithToken.Content.ReadAsStringAsync().Result); //3. visit no auth service
Console.WriteLine("\nNo Auth Service Here ");
client.DefaultRequestHeaders.Clear();
var res = client.GetAsync("/api/Counter/Count").Result; Console.WriteLine($"Send Request to /api/Counter/Count");
Console.WriteLine($"Result : {res.StatusCode}");
Console.WriteLine(res.Content.ReadAsStringAsync().Result); Console.Read();
} private static string GetJwt()
{
HttpClient client = new HttpClient(); client.BaseAddress = new Uri( "http://localhost:9000");
client.DefaultRequestHeaders.Clear(); var res2 = client.GetAsync("/authapi/auth?name=catcher&pwd=123").Result; dynamic jwt = JsonConvert.DeserializeObject(res2.Content.ReadAsStringAsync().Result); return jwt.access_token;
}
}

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. python_机器学习_监督学习模型_决策树

    决策树模型练习:https://www.kaggle.com/c/GiveMeSomeCredit/overview 1. 监督学习--分类 机器学习肿分类和预测算法的评估: a. 准确率 b.速度 ...

  2. Ubuntu 16.04/18.04 右键创建新建文件

    刚刚安装完新的Ubuntu系统后不能直接右键创建新的文件,那么怎么做呢 办法: 打开终端,cd 切换到 Templates文件夹下,然后输入: sudo gedit text 这样就在Template ...

  3. MLflow安装配置初入门

    学习这个时,要和Kubeflow作比较, 看看它们俩在解决和规范机器学习流程方面的思路异同. mlflow三大内涵: Tracking, Projects, Models. 一,基础镜像 harbor ...

  4. pdfium 之二

    https://www.foxitsoftware.cn/products/premium-pdfium/feature.php 基于谷歌PDFium开源代码 谷歌采用福昕的PDF技术为其PDF开源项 ...

  5. flask 案例项目基本框架的搭建

    综合案例:学生成绩管理项目搭建 一 新建项目目录students,并创建虚拟环境 mkvirtualenv students 二 安装开发中使用的依赖模块 pip install flask==0.1 ...

  6. day6_7.4总结数据类型的可变不可变

    续昨天: 列表的常用方法: 1.chear() 用途:清空列表,其返回值无,返回none. list1=[1,2,3,4,5] a=list1.clear() print(list1) print(a ...

  7. RST复位报文

    复位报文段: 一些特殊情况,TCP一端向另一端发送复位报文,以通知对方关闭链接或者重新建立链接. 产生复位报文的三种情况: 1. 当客户端访问一个不存在的端口时,目标主机会给客户端发送一个复位报文段. ...

  8. dateNode 启动不了

    dateNode 启动不了 进去路径中找到  name和data文件夹,current下面分别有 一个 version文件,打开发现两个clusterId都不一样 把name和data文件里面的ver ...

  9. zz独家专访AI大神贾扬清:我为什么选择加入阿里巴巴?

    独家专访AI大神贾扬清:我为什么选择加入阿里巴巴? Natalie.Cai 拥有的都是侥幸,失去的都是人生 ​关注她 5 人赞同了该文章 本文由 「AI前线」原创,原文链接:独家专访AI大神贾扬清:我 ...

  10. LG2578 「ZJOI2005」九数码游戏 bfs

    问题描述 LG2578 题解 用string+map去重. bfs即可. \(\mathrm{Code}\) #include<bits/stdc++.h> using namespace ...