一 使用缘由

最近写微服务的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使用案例的更多相关文章

  1. 在项目中自定义集成IdentityService4

    OAuth2.0协议 在开始之前呢,需要我们对一些认证授权协议有一定的了解. OAuth 2.0 的一个简单解释 http://www.ruanyifeng.com/blog/2019/04/oaut ...

  2. 数据库优化案例——————某市中心医院HIS系统

    记得在自己学习数据库知识的时候特别喜欢看案例,因为优化的手段是容易掌握的,但是整体的优化思想是很难学会的.这也是为什么自己特别喜欢看案例,今天也开始分享自己做的优化案例. 最近一直很忙,博客产出也少的 ...

  3. SQL Server内存遭遇操作系统进程压榨案例

    场景: 最近一台DB服务器偶尔出现CPU报警,我的邮件报警阈(请读yù)值设置的是15%,开始时没当回事,以为是有什么统计类的查询,后来越来越频繁. 探索: 我决定来查一下,究竟是什么在作怪,我排查的 ...

  4. solr_架构案例【京东站内搜索】(附程序源代码)

    注意事项:首先要保证部署solr服务的Tomcat容器和检索solr服务中数据的Tomcat容器,它们的端口号不能发生冲突,否则web程序是不可能运行起来的. 一:solr服务的端口号.我这里的sol ...

  5. Yeoman 官网教学案例:使用 Yeoman 构建 WebApp

    STEP 1:设置开发环境 与yeoman的所有交互都是通过命令行.Mac系统使用terminal.app,Linux系统使用shell,windows系统可以使用cmder/PowerShell/c ...

  6. 了不起的 nodejs-TwitterWeb 案例 bug 解决

    了不起的nodejs算是一本不错的入门书,不过书中个别案例存在bug,按照书中源码无法做出和书中相同效果,原本兴奋的心情掺杂着些许失落. 现在我们看一下第七章HTTP,一个Twitter Web客户端 ...

  7. 一个表缺失索引发的CPU资源瓶颈案例

    背景 近几日,公司的应用团队反应业务系统突然变慢了,之前是一直比较正常.后与业务部门沟通了解详情,得知最近生意比较好,同时也在做大的促销活动,使得业务数据处理的量出现较大的增长,最终系统在处理时出现瓶 ...

  8. 【Machine Learning】决策树案例:基于python的商品购买能力预测系统

    决策树在商品购买能力预测案例中的算法实现 作者:白宁超 2016年12月24日22:05:42 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本 ...

  9. Redis简单案例(二) 网站最近的访问用户

    我们有时会在网站中看到最后的访问用户.最近的活跃用户等等诸如此类的一些信息.本文就以最后的访问用户为例, 用Redis来实现这个小功能.在这之前,我们可以先简单了解一下在oracle.sqlserve ...

随机推荐

  1. LeetCode:至少是其他数字两倍的最大数【747】

    LeetCode:至少是其他数字两倍的最大数[747] 题目描述 在一个给定的数组nums中,总是存在一个最大元素 . 查找数组中的最大元素是否至少是数组中每个其他数字的两倍. 如果是,则返回最大元素 ...

  2. 正则表达式test match exec search

    (1)((2))(3)   $1  是第一个括号 $2  是第二个括号 $3  是第二个括号中的括号 $4  是第三个括号     http://www.jb51.net/article/28007. ...

  3. Safari通过JavaScript获取系统语言

      IE6 IE7 IE8 Firefox Chrome Safari Opera navigator.language undefined zh-CN zh-CN navigator.userLan ...

  4. nodejs爬虫selenium

    6.元素操作 查找元素 使用操作如何找到页面元素Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找.下面介绍几种比较常用的方法. By ID假 ...

  5. 缩略图悬浮效果的jQuery焦点图

    在线演示 本地下载

  6. SQL Server获取数据库的当前连接状态

    SELECT * FROM [Master].[dbo].[SYSPROCESSES] WHERE [DBID]=(SELECT [DBID] FROM [Master].[dbo].[SYSDATA ...

  7. Android系统--Binder系统具体框架分析(一)补充

    Android系统--Binder系统具体框架分析(一)补充 补充:对Binder驱动分析一的代码补充,添加saygoobye和saygoodbye_to服务 test_server.h #ifnde ...

  8. 如何判断Linux服务器是否被入侵?

    被入侵服务器的症状 当服务器被没有经验攻击者或者自动攻击程序入侵了的话,他们往往会消耗 100% 的资源.他们可能消耗 CPU 资源来进行数字货币的采矿或者发送垃圾邮件,也可能消耗带宽来发动 DoS ...

  9. Windows Server 2008 架设 Web 服务器教程(图文详解)

    Windows Server 2008 架设 Web 服务器教程(图文详解) 一.安装 IIS 7.0 : 虽然 Windows Server 2008 内置了I IS 7.0,但是默认情况下并没有安 ...

  10. 【codevs1028】花店橱窗布置(费用流)

    这几天刚学了费用流,找到了这道题来练一练手. 题目: 题目描述 Description 假设以最美观的方式布置花店的橱窗,有F束花,V个花瓶,我们用美学值(一个整数)表示每束花放入每个花瓶所产生的美学 ...