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 ...
随机推荐
- ElasticSearch监控
1. elasticsearch 服务的监控与报警 http://bigbo.github.io/pages/2016/10/20/elasticsearch_monitor/ 2. How to m ...
- imx6qsbd lvds dtc
lvds显示屏调试参考 1.基于飞思卡尔imxsolosabresd开发板Linux-3.10.53 lvds屏幕调试: http://blog.csdn.net/qq_37375427/articl ...
- display:inline-block 间隙
IE6/7是不支持display:inline-block属性,只是让其表现的跟inline-block一样,尤其对于inline水平的元素,其表现度可以用perfect一词来形容了. 对于IE8+以 ...
- CentOS 6.5下Redmine的安装配置
首先引用百度介绍下redmine: Redmine是用Ruby开发的基于web的项目管理软件,是用ROR框架开发的一套跨平台项目管理系统,据说是源于Basecamp的ror版而来,支持多种数据库,有不 ...
- python批量修改文件名称
参考文章:http://www.cnblogs.com/ma6174/archive/2012/05/04/2482378.html 最近遇到一个问题,在网上下载了一批视频课程,需要将每节课的名称标号 ...
- Optional int parameter 'time' is present but cannot be translated into a null value due to being decla
今天在操作redis的时候报了这个错:Optional int parameter 'time' is present but cannot be translated into a null val ...
- 【P2405】方格取数问题加强版(费用流)
考虑如何建图.还是老样子先拆点,然后把每两个点之间连接两条边,一条流量为1,费用为-点权,处理是否走这个点.一条流量无限,没有费用,因为哪怕一个点选过了,它的地方还是可以重复走过去的. 然后把经由一个 ...
- 【bzoj3240 && 洛谷P1397】矩阵游戏[NOI2013](矩阵乘法+卡常)
题目传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3240 这道题其实有普通快速幂+费马小定理的解法……然而我太弱了,一开始只想到了矩阵乘法的 ...
- java hasmap对象的深复制实现:字节码复制和对象序列化成字符串复制比较。
/** * Created by Administrator on 2016/11/23. */ public class test { public static void main(String[ ...
- MVC 绑定 下拉框数据
HTML: <div class="form-group col-sm-12"> <div class="col-sm-4"> < ...