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. pip包管理工具 基本使用

    # 简介 pip是一款包管理工具, 和apt, yum, brew功能类似 # 安装 wget --no-check-certificate https://bootstrap.pypa.io/get ...

  2. 机器学习---朴素贝叶斯与逻辑回归的区别(Machine Learning Naive Bayes Logistic Regression Difference)

    朴素贝叶斯与逻辑回归的区别: 朴素贝叶斯 逻辑回归 生成模型(Generative model) 判别模型(Discriminative model) 对特征x和目标y的联合分布P(x,y)建模,使用 ...

  3. Linux启动与停止Tomcat

    停止Tomcat: cd 切换到Tomcat的bin目录下,关闭命令:[root@localhost bin]# ./shutdown.sh 检查tomcat是否已关闭,检查命令:[root@loca ...

  4. x32下的DLL隐藏

    原理主要就是PEB 中模块断链. 这里整理下代码.原理可以看下另一篇我写的帖子. https://www.cnblogs.com/iBinary/p/9601860.html // dllmain.c ...

  5. 用docker构建redis cluster

    下面内容大部分借鉴自: http://louz.github.io/2016/08/11/docker-redis-cluster/ docker pull redis:3.0.7 #映射6379端口 ...

  6. Spark2.x(六十):在Structured Streaming流处理中是如何查找kafka的DataSourceProvider?

    本章节根据源代码分析Spark Structured Streaming(Spark2.4)在进行DataSourceProvider查找的流程,首先,我们看下读取流数据源kafka的代码: Spar ...

  7. IDEA把spring-boot项目打包成jar

    1.打开项目,然后右击项目选中‘Open Module Settings’进入project Structure( 快捷键 Ctrl+Shift+Alt+S或者File->Project Str ...

  8. linux学习(4):linux常用命令(50个)

    linux常用命令(50个) 1. find 基本语法参数如下: find [PATH] [option] [action] # 与时间有关的参数: -mtime n : n为数字,意思为在n天之前的 ...

  9. 函数式接口, Collection等

    Lambda 函数式接口 lambda 表达式的使用需要借助于 函数式接口, 也就是说只有函数式接口才可以将其用 lambda 表达式进行简化. 函数式接口定义为仅含有一个抽象方法的接口. 按照这个定 ...

  10. Linux零拷贝技术 直接 io

    Linux零拷贝技术 .https://kknews.cc/code/2yeazxe.html   https://zhuanlan.zhihu.com/p/76640160 https://clou ...