identityservice4使用案例
一 使用缘由
最近写微服务的blog,研读了o’reilly出的 《building Microservices With Asp.net Core》,其中使用的微服务分布式权限组件是microsoft.aspnetcore.authentication.jwtbearer,那最近identityserver4这么流行,就决定替换掉它。
二 开始
1 认证流程:

2 开发
认证服务器:
(1) 首先一个空的asp.net core 项目,在nuget包中安装identityserver4 包
(2) 项目组织,会增加Config.cs的文件。

相关代码:
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace Walt.Freamwork.Sec
{
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
} public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client", // no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials, // secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" }
}
};
}
}
}
public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and resources
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
services.AddMvc();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseMvc((route) => {
route.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
被请求资源服务器
(1)为webapi增加identityserver4.accesstokenvalidation包
(2) 配置
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:64433"; //授权服务器
options.RequireHttpsMetadata = false; options.ApiName = "api1";
});
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var log= LoggerFac.CreateLogger<Startup>();
log.LogInformation("infomation");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication(); //使用认证
app.UseHttpsRedirection();
app.UseMvc();
}
客户端:从代码中可以看出,分两步,第一步获取token
,第二部根据token去访问需要的服务。
using System;
using System.Net.Http;
using IdentityModel.Client;
using IdentityServer4;
using Newtonsoft.Json.Linq; namespace Walt.Freamwork.Sec.Client
{
class Program
{
static void Main(string[] args)
{
var disco = DiscoveryClient.GetAsync("http://localhost:64433/").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
} // request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = tokenClient.RequestClientCredentialsAsync("api1").Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json); // call api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken); var response = client.GetAsync("http://localhost:50403/api/identity").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(JArray.Parse(content));
} Console.ReadKey();
}
}
}
运行情况:咱们为webapi定义一个api
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace Walt.Freamwork.Sec
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}

如果不带token
using System;
using System.Net.Http;
using IdentityModel.Client;
using IdentityServer4;
using Newtonsoft.Json.Linq; namespace Walt.Freamwork.Sec.Client
{
class Program
{
static void Main(string[] args)
{
var disco = DiscoveryClient.GetAsync("http://localhost:64433/").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
} // request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = tokenClient.RequestClientCredentialsAsync("api1").Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json); // call api
var client = new HttpClient();
// client.SetBearerToken(tokenResponse.AccessToken); 这块注释掉了 var response = client.GetAsync("http://localhost:50403/api/identity").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(JArray.Parse(content));
} Console.ReadKey();
}
}
}

总结:本实例使用的是声明的方式认证,也可以使用用户名密码。 identityserver4是个功能强大但是使用很简洁的一个认证框架,
也支持OAUTH为外部认证提供支持,这里就不讨论了。
identityservice4使用案例的更多相关文章
- 在项目中自定义集成IdentityService4
OAuth2.0协议 在开始之前呢,需要我们对一些认证授权协议有一定的了解. OAuth 2.0 的一个简单解释 http://www.ruanyifeng.com/blog/2019/04/oaut ...
- 数据库优化案例——————某市中心医院HIS系统
记得在自己学习数据库知识的时候特别喜欢看案例,因为优化的手段是容易掌握的,但是整体的优化思想是很难学会的.这也是为什么自己特别喜欢看案例,今天也开始分享自己做的优化案例. 最近一直很忙,博客产出也少的 ...
- SQL Server内存遭遇操作系统进程压榨案例
场景: 最近一台DB服务器偶尔出现CPU报警,我的邮件报警阈(请读yù)值设置的是15%,开始时没当回事,以为是有什么统计类的查询,后来越来越频繁. 探索: 我决定来查一下,究竟是什么在作怪,我排查的 ...
- solr_架构案例【京东站内搜索】(附程序源代码)
注意事项:首先要保证部署solr服务的Tomcat容器和检索solr服务中数据的Tomcat容器,它们的端口号不能发生冲突,否则web程序是不可能运行起来的. 一:solr服务的端口号.我这里的sol ...
- Yeoman 官网教学案例:使用 Yeoman 构建 WebApp
STEP 1:设置开发环境 与yeoman的所有交互都是通过命令行.Mac系统使用terminal.app,Linux系统使用shell,windows系统可以使用cmder/PowerShell/c ...
- 了不起的 nodejs-TwitterWeb 案例 bug 解决
了不起的nodejs算是一本不错的入门书,不过书中个别案例存在bug,按照书中源码无法做出和书中相同效果,原本兴奋的心情掺杂着些许失落. 现在我们看一下第七章HTTP,一个Twitter Web客户端 ...
- 一个表缺失索引发的CPU资源瓶颈案例
背景 近几日,公司的应用团队反应业务系统突然变慢了,之前是一直比较正常.后与业务部门沟通了解详情,得知最近生意比较好,同时也在做大的促销活动,使得业务数据处理的量出现较大的增长,最终系统在处理时出现瓶 ...
- 【Machine Learning】决策树案例:基于python的商品购买能力预测系统
决策树在商品购买能力预测案例中的算法实现 作者:白宁超 2016年12月24日22:05:42 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本 ...
- Redis简单案例(二) 网站最近的访问用户
我们有时会在网站中看到最后的访问用户.最近的活跃用户等等诸如此类的一些信息.本文就以最后的访问用户为例, 用Redis来实现这个小功能.在这之前,我们可以先简单了解一下在oracle.sqlserve ...
随机推荐
- MySQL数据库(6)_用户操作与权限管理、视图、存储过程、触发器、基本函数
用户操作与权限管理 MySQL用户操作 创建用户 方法一: CREATE USER语句创建 CREATE USER "用户名"@"IP地址" IDENTIFIE ...
- ThinkPHP框架基础知识一
ThinkPHP是一个快速.兼容而且简单的轻量级国产PHP开发框架,诞生于2006年初,原名FCS,2007年元旦正式更名为ThinkPHP,遵循Apache2开源协议发布,从Struts结构移植过来 ...
- PAT 天梯赛 L1-031. 到底是不是太胖了 【水】
题目链接 https://www.patest.cn/contests/gplt/L1-031 AC代码 #include <iostream> #include <cstdio&g ...
- token的生成和应用
token的生成和应用 接口特点汇总: 1.因为是非开放性的,所以所有的接口都是封闭的,只对公司内部的产品有效: 2.因为是非开放性的,所以OAuth那套协议是行不通的,因为没有中间用户的授权过程: ...
- Js 类型方面的神坑
你有没有遇见过本来好好的一个数组结果 typeof 出来是个 object 的情况,你有没有遇到过非要写个 typeof x === "undefined" 判断未赋值的情况... ...
- 20145231《Java程序设计》课程总结
20145231 <Java程序设计>课程总结 每周读书笔记链接汇总 ● 20145231<Java程序设计>第一周学习总结 ●20145231<Java程序设计> ...
- QQ空间如何设置被删除的好友不能访问空间
原来一直都很在乎.自己看着办. 经过简单的测试这种方法还是可以的啊,有问题到时候在说吧.理论上无论是否删除好友都可以限制对方访问空间. 旁边还有可以设置不能访问的名单(看仔细点-设置限制名单).
- Kubernetes 待学习列表
1.EFK or ELK https://blog.csdn.net/mawming/article/details/78344939, https://www.jianshu.com/p/fe3ac ...
- [转载]Spring配置文件详解一:
原文地址:与base-package="com.xx">Spring配置文件详解一:<context:annotation-config/>与<contex ...
- 主席树----POJ 2104(主席树裸题)(转)
首先来介绍一下我们需求:给你n个数,多次问你某个区间内的第k小是哪个数 主席树: 主席树的全名应该是 函数式版本的线段树.加上附带的一堆 technology.. ..总之由于原名字太长了,而且 “主 ...