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. PE安装器说明by双心

    PE安装器说明by双心http://www.cnblogs.com/liuzhaoyzz/p/4204262.htmlhttps://share.weiyun.com/5749g5p基于omnifs3 ...

  2. Matlab下的文件执行路径

    Matlab下有时命令出错,源于Command窗口的路径不正确.快捷键的执行会受此影响.

  3. USACO 2009 Feb 股票市场 Stock Market

    USACO 2009 Feb 股票市场 Stock Market Description 尽管奶牛们天生谨慎,她们仍然在住房抵押信贷市场中大受打击,现在她们准备在股市 上碰碰运气.贝西开挂了,她知道S ...

  4. mysql 分组和排序

    mysql> select * from table1; +----------+------------+-----+---------------------+ | name_new | t ...

  5. SDN阅读作业

    阅读文章<软件定义网络(SDN)研究进展>,并根据所阅读的文章,书写一篇博客,回答以下问题(至少3个): 1.为什么需要SDN?SDN特点? 随着网络规模的不断扩大,传统网络设备繁复的协议 ...

  6. Java 12 骚操作, String居然还能这样玩!

    Java 13 都快要来了,12必须跟栈长学起! Java 13 即将发布,新特性必须抢先看! 栈长之前在Java技术栈微信公众号分享过<Java 11 已发布,String 还能这样玩!> ...

  7. 范仁义html+css课程---4、文本标签

    范仁义html+css课程---4.文本标签 一.总结 一句话总结: 文本标签大致掌握一下,做到它站在你对面的时候最好认得,认不得也没关系,直接百度 1.ins标签.u标签和del标签 作用? ins ...

  8. ubuntu16.04 安装使用meld及问题

    本文链接:https://blog.csdn.net/ai_liuliu/article/details/95504095安装meldsudo apt-get install meld启动meld方法 ...

  9. mariadb 10.2/mysql 8.0实现递归

    借助mysql 8.0的cte(它是iso sql标准的一部分),可以实现递归,mariadb 10.2.2开始支持递归cte,如下: +----+----------+--------------+ ...

  10. 008 webpack的其他使用方式

    一:配置 1.配置文件 每次修改main文件,重新打包都要指定入口与出口,比较费事,可以使用配置文件的方式 在根目录下新建webpack.config.js: const path = require ...