这个篇文章主要是记录自己参考官方文档搭建身份认证的过程

使用的.NET Core2.2

参考地址:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html

1.第一步,创建一个webapi的工程,要使用IDS4(IdentityServer4)做身份认证首先得在程序管理控制台导入IDS4的NuGet包:Install-Package IdentityServer4

2.因为客户端凭证的方式会在api根目录下生成一个tempkey.rsa文件,所以需要在在Starut.cs构造函数中注入IHostingEnvironment

         public IHostingEnvironment Environment { get; }
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
Configuration = configuration;
Environment = environment;
}

3.导入IDS4的包之后我们需要在ConfigureServices中添加如下内容:

 var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
//.AddTestUsers(Config.GetUsers()); services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
#region 客户端凭证的方式需要添加此处代码生成证书
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
else
{
throw new Exception("need to configure key material");
}
#endregion services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
//开发环境禁用了https,默认为开开启
options.RequireHttpsMetadata = false; options.Audience = "api1";
});

4.在Configure中添加identityServer中间件:

//在UseMvc之前即可
app.UseIdentityServer();

然后我们在VaulesController中修改下代码,在后面客户端的时候用来测试

    [Route("api/[controller]")]
[Authorize]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}

客户端需要导入IdentityModel Nuget包

下面代码中GetDiscoveryDocumentAsync()方法主要是从API服务的http://localhost:5000/.well-known/openid-configuration获取访问token的接口,即TokenEndpoint,debug可看到TokenEndpoint=http://localhost:5000/connect/token,经过验证直接将Addres赋值为http://localhost:5000/connect/token也是可以正常获取token的,查看IdentityModel源码也是在url中追加了/.well-known/openid-configuration

  var  _client = new HttpClient(); 

  var disco = _client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
}
 var tokenResponse = _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{ Address = disco.TokenEndpoint,
//Address="http://localhost:5000/connect/token",//直接使用获取token的地址
ClientId = "client",
ClientSecret = "secret",
Scope = "api1"
}).Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
Console.ReadKey();
return;
}
Console.WriteLine("============================客户端获取token================================================");
Console.WriteLine(tokenResponse.Json); _client.SetBearerToken(tokenResponse.AccessToken);
var response = _client.GetAsync("http://localhost:5000/api/Values").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(JArray.Parse(content));
}

以下是运行之后的结果

IdentityServer4(一)使用客户端凭证方式的更多相关文章

  1. IdentityServer4系列 | 客户端凭证模式

    一.前言 从上一篇关于 快速搭建简易项目中,通过手动或者官方模板的方式简易的实现了我们的IdentityServer授权服务器搭建,并做了相应的配置和UI配置,实现了获取Token方式. 而其中我们也 ...

  2. IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API

    IdentityServer4 中文文档 -9- (快速入门)使用客户端凭证保护API 原文:http://docs.identityserver.io/en/release/quickstarts/ ...

  3. ASP.NET Core3.1使用IdentityServer4中间件系列随笔(三):创建使用[ClientCredentials客户端凭证]授权模式的客户端

    配套源码:https://gitee.com/jardeng/IdentitySolution 上一篇<ASP.NET Core3.1使用IdentityServer4中间件系列随笔(二):创建 ...

  4. IdentityServer4系列 | 资源密码凭证模式

    一.前言 从上一篇关于客户端凭证模式中,我们通过创建一个认证授权访问服务,定义一个API和要访问它的客户端,客户端通过IdentityServer上请求访问令牌,并使用它来控制访问API.其中,我们也 ...

  5. Atitit 动态调用webservice与客户端代理方式调用

    Atitit 动态调用webservice与客户端代理方式调用 方式1: 使用call.invoke  直接调用WSDL,缺点:麻烦,不推荐--特别是JAVA调用.NET的WS时,会有不少的问题需要解 ...

  6. Web Service基础——四种客户端调用方式

    通过访问公网服务地址 http://www.webxml.com.cn/zh_cn/index.aspx 来演示四种不同的客户端调用方式 1. 生成客户端调用方式 1.1 Wsimport命令介绍 首 ...

  7. 因为 Java 和 Php 在获取客户端 cookie 方式不同引发的 bug

    遇到个 Java 和 Php 在获取客户端 cookie 方式不同导致跨系统的问题.所以写了这篇博客梳理下相关知识. 实验 下面通过两个简单的实验,来看Java和Php在获取web请求中的cookie ...

  8. asp.net core IdentityServer4 实现 Client credentials(客户端凭证)

    前言 OAuth 2.0默认四种授权模式(GrantType) 授权码模式(authorization_code) 简化模式(implicit) 密码模式(resource owner passwor ...

  9. IdentityServer4关于多客户端和API的最佳实践【含多类型客户端和API资源,以及客户端分组实践】【下】

    经过前两篇文章你已经知道了关于服务器搭建和客户端接入相关的基本资料,本文主要讲述整个授权系统所服务的对象,以ProtectApi资源为演示 目标: 1)实现多资源服务器针对请求的token校验,接入I ...

随机推荐

  1. easyui获取选中行上一行的数据

    text: 'XX',            iconCls: 'icon-ok',            handler: function () {                var rowI ...

  2. thinkphp5.0验证的封装

    刚学完这个验证器封装,刚开始还是有点晕的,后面仔细看了两遍,才慢慢感觉到了继承这个方法的好处,看来还得慢慢锻炼锻炼; 问题:结合上篇的自定义验证器,发现每次使用验证器都重复这样写代码;//验证器$va ...

  3. 2018-2019-2 网络对抗技术 20165228 Exp1 PC平台逆向破解

    2018-2019-2 网络对抗技术 20165228 Exp1 PC平台逆向破解 实验内容及步骤 第一部分:直接修改程序机器指令,改变程序执行流程 关键:通过修改call指令跳转的地址,将原本指向被 ...

  4. Python Redis中Scan遇到问题

    在项目启动中需要删除redis原先相同key储存的值,所以使用scan_iter来便利相关的key,并删除. 这里需要注意两个性能问题 1. scan_iter的模糊匹配的过滤器要正确,否则会带来很多 ...

  5. 64位ubuntu16.04系统安装网易云音乐

    64位ubuntu16.04系统安装网易云音乐 1.官网下载安装包:netease-cloud-music_1.1.0_amd64_ubuntu.deb https://music.163.com/# ...

  6. 更改手机系统的User-Agent & okhttp

    okhttp 和 volley 1. 之前用的是volley,其中一部分功能,比如User-Agent,是系统去处理的,改成okhttp库后,这部分功能需要浏览器自己处理 2. 具体区别可以参考: h ...

  7. VS Code引用 vue/cli

    npm i @vue/cli -g    引用cli脚手架 3.0版本 下载好后 找个空文件夹  vue create myvue 创建vue项目   myvue是自己项目名称 Your connec ...

  8. PTA9

    这个作业属于哪个课程 C语言程序设计2 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/software-engineering-class2-2018/ ...

  9. requests 爬虫

    爬虫 常用爬虫爬取网页,但如果一直爬取会被ban掉,因此需要对爬虫进行一些改进反反爬 使用requests和beautifulsoup4构建爬虫,1.随机user-agent:2.ip代理:4.coo ...

  10. Linux第九节课学习笔记

    fdisk可添加.删除.转换分区. 创建主分区:n-p-w:扩展分区:n-e:逻辑分区:n-l. SWAP分区专用格式化命令mkswap,专用挂载命令swapon. 磁盘容量配额中,硬限制必须,软限制 ...