1.新建三个项目

IdentityServer:端口5000

IdentityAPI:端口5001

IdentityClient:

2.在IdentityServer项目中添加IdentityServer4的包:Install-Package IdentityServer4

添加一个类:

        public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api", "myapi")//定义资源名称
};
} public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",//客户端获取token时指定的ClientId值
AllowedGrantTypes = GrantTypes.ClientCredentials,//授权模式 ClientSecrets =
{
new Secret("secret".Sha256())//客户端获取token时指定的Secret值
},
AllowedScopes = { "api" }//设置可访问的资源名称
}
};
}

然后在该项目的Startup中注入:

    public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//注入到容器中
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())//加载配置信息
.AddInMemoryClients(Config.GetClients());
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer();//管道
}
}

然后你可以访问http://localhost:5000/.well-known/openid-configuration

3.在IdentityAPI项目中添加一个控制器:控制器头要添加[Authorize]

添加身份验证中间件:① 验证传入令牌以确保它来自可信发行者,② 令牌验证是有效的,用于在这个API

Microsoft.AspNetCore.Authentication.JwtBearer

在该项目的Startup文件中

    public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters(); services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options => //使用IdentityServer作为授权模式
{
options.Authority = "http://localhost:5000";//服务地址
options.RequireHttpsMetadata = false; options.ApiName = "api";//访问的资源名称
});
} public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvc();
}
}

4.IdentityClient项目中添加IdentityModel 库

IdentityModel 包含了一个用于发现端点的客户端库。这样一来你只需要知道 IdentityServer 的基础地址,实际的端点地址可以从元数据中读取。

        private static async Task MainAsync()
{
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
} // request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api"); if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n"); // call api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("http://localhost:5001/Home");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
Console.Read();
}

客户端授权模式通常用于服务器到服务器通信

IdentityServer4(客户端授权模式)的更多相关文章

  1. IdentityServer4 (1) 客户端授权模式(Client Credentials)

    写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...

  2. IdentityServer4[3]:使用客户端认证控制API访问(客户端授权模式)

    使用客户端认证控制API访问(客户端授权模式) 场景描述 使用IdentityServer保护API的最基本场景. 我们定义一个API和要访问API的客户端.客户端从IdentityServer请求A ...

  3. IdentityServer(二)客户端授权模式

    前言 客户端授权模,客户端直接向Identity Server申请token并访问资源.客户端授权模式比较适用于服务之间的通信. 搭建Identity服务 新建名为 IdentityServer 的W ...

  4. 认证授权:IdentityServer4 - 各种授权模式应用

    前言: 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例 授权模式: 环境准备 a)调整项目结构如下:   b)调整cz.Id ...

  5. IdentityServer4 自定义授权模式

    IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode.ClientCredentials.Password.RefreshToken.DeviceCode), ...

  6. IdentityServer4(7)- 使用客户端认证控制API访问(客户端授权模式)

    一.前言 本文已更新到 .NET Core 2.2 本文包括后续的Demo都会放在github:https://github.com/stulzq/IdentityServer4.Samples (Q ...

  7. AspNetCore中的IdentityServer4客户端认证模式实现

    1 AuthorizationServer using IdentityServer4; using IdentityServer4.Models; public class Startup { pu ...

  8. IdentityServer4 (3) 授权码模式(Authorization Code)

    写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...

  9. (十)React Ant Design Pro + .Net5 WebApi:后端环境搭建-IdentityServer4(二)授权模式

    一.前言 先交代一下整个Demo项目结构: 一个认证服务(端口5000)IdentityServer4.Authentication 五个授权模式(两个控制台程序,三个MVC项目端口5001)文件夹G ...

随机推荐

  1. The two of the oldest man need cheers

    At a company dinner, the drinking rule was that two colleagues of similar age clinked glasses of win ...

  2. SVN 常用 还原项目

    1.先修改本来两个文件,然后再提交到SVN 2.在日志界面,查看提交的文件,找到对应的版本号 3.找到对应的版本号(这里的版本号是1995,我提交生成的版本号 的前一个版本 才是我未作出修改的版本), ...

  3. 虚拟变量陷阱(Dummy Variable Trap)

    虚拟变量陷阱(Dummy Variable Trap):指当原特征有m个类别时,如果将其转换成m个虚拟变量,就会导致变量间出现完全共线性的情况. 假设我们有一个特征“性别”,包含男性和女性两个类别,如 ...

  4. 阿里云部署自己的web服务器

    阿里云部署自己的web服务器 [外链图片转存失败(img-GIKNTPPx-1564287221547)(https://upload-images.jianshu.io/upload_images/ ...

  5. 咕泡学院java架构vip课程

    1.wps文档地址 https://docs.qq.com/doc/DRVNLUndvTmFSdEhO 2.百度网盘地址 https://pan.baidu.com/s/1uxaTzJZHKrsw_H ...

  6. hdfs、yarn集成kerberos

    1.kdc创建principal 1.1.创建认证用户 登陆到kdc服务器,使用root或者可以使用root权限的普通用户操作: # kadmin.local -q “addprinc -randke ...

  7. 后退欧拉法求解常微分方程(c++)

    #include<iostream> #include<iomanip> using namespace std; int main() { double x,y,yn,h,t ...

  8. Git bash Error: Could not fork child process: There are no available terminals (-1)

    错误信息:Error: Could not fork child process: There are no available terminals (-1) 截图如下: 解决办法: (1)使用cmd ...

  9. Server 2003 操作系统位数

    安装好电脑系统,如何查看windows 2003/xp/win7是64位还是32位? 方法/步骤 第一种方法:桌面上鼠标右键单击“计算机”(我的电脑) 在弹出的快捷菜单中选择“属性”,如果看到64的字 ...

  10. 帆软 联合 创始人 数据可视化 中国 发展 FineReport FineBI

    丧心病狂!帆软公司的成立竟源于一个被初恋抛弃的程序员 - 大数据-炼数成金-Dataguru专业数据分析社区http://dataguru.cn/article-7500-1.html 帆软联合创始人 ...