IdentityServer4[4]使用密码保护API资源
使用密码保护API资源(资源所有者密码授权模式)

资源所有者(Resource Owner)就是指的User,也就是用户。所以也称为用户名密码模式。相对于客户端凭证模式,增加了一个参与者User。通过User的用户名和密码向IdentityServer申请Access Token。这种模式下要求客户端不能存储密码,否则就存在密码泄露的风险,但是又不能确保第三方Client不存储密码。所以这种模式仅适用于受信任的客户端。
创建项目
IdentityServer的ASP.NET Core Web空项目,端口5000
Api的ASP.NET Core Web API项目,端口5001
Client的控制台项目

IdentityServer准备工作
定义API资源
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>()
{
new ApiResource("api","My Api")
};
}
定义客户端
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId="pwdclient",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {"api"}
}
};
}
配置IdentityServer
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
API准备
在API控制器上,增加[Authorize]特性(授权)
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
Startup增加如下代码:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
//options.ApiName = "Home";//不设置此参数,代表所有接口全部使用权限
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
使用postman调用

创建客户端
IdentityModel 包括用于发现 IdentityServer 各个终结点(EndPoint)的客户端库。这样只需要知道 IdentityServer 的地址 - 可以从元数据中读取实际的各个终结点地址:
var client = new HttpClient();
var disdoc = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
if (disdoc.IsError)
{
Console.WriteLine(disdoc.Error);
}
获取token
var tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest()
{
Address = disdoc.TokenEndpoint,
ClientId = "pwdclient",
ClientSecret = "secret",
Scope = "api",
UserName = "Test1",
Password = "123456"
}).Result;
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
}
else
{
Console.WriteLine(tokenResponse.Json);
}
调用API
HttpClient httpClient = new HttpClient();
httpClient.SetBearerToken(tokenResponse.AccessToken);
var response = httpClient.GetAsync("http://localhost:5001/api/values").Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
IdentityServer4[4]使用密码保护API资源的更多相关文章
- IdentityServer4 中文文档 -10- (快速入门)使用密码保护API
IdentityServer4 中文文档 -10- (快速入门)使用密码保护API 原文:http://docs.identityserver.io/en/release/quickstarts/2_ ...
- 【IdentityServer4文档】- 使用密码保护 API
使用密码保护 API OAuth 2.0 协议允许资源拥有者给客户端密码授权:客户端向令牌服务发送用户密码,以获取代表该用户的访问令牌. 该规范建议仅将“资源所有者密码授予”用于“可信”(或旧版)应用 ...
- IdentityServer4关于多客户端和API的最佳实践【含多类型客户端和API资源,以及客户端分组实践】【下】
经过前两篇文章你已经知道了关于服务器搭建和客户端接入相关的基本资料,本文主要讲述整个授权系统所服务的对象,以ProtectApi资源为演示 目标: 1)实现多资源服务器针对请求的token校验,接入I ...
- asp.net core系列 55 IS4使用Identity密码保护API
一.概述 OAuth 2.0资源(web api)所有者密码授权,允许客户端(Client项目)向令牌服务(IdentityServer项目)发送用户名和密码,并获取代表该用户的访问令牌.在官方文档中 ...
- asp.net core系列 55 IS4结合Identity密码保护API
一.概述 OAuth 2.资源所有者密码授权允许客户端(Client项目)向令牌服务(IdentityServer项目)发送用户名和密码,并获取代表该用户的访问令牌.本篇将IS4结合asp.net c ...
- Identity Server 4 - Hybrid Flow - 保护API资源
这个系列文章介绍的是Identity Server 4 的 Hybrid Flow, 前两篇文章介绍了如何保护MVC客户端, 本文介绍如何保护API资源. 保护MVC客户端的文章: https://w ...
- 基于IdentityServer4的单点登录——Api
1.新建项目并添加引用 新建一个asp .net core 2.0的项目引用IdentityServer4.AccessTokenValidation 2.配置 将Api与IdentityServer ...
- Identity Server 4 - Hybrid Flow - 使用ABAC保护MVC客户端和API资源
这个系列文章介绍的是Identity Server 4 实施 OpenID Connect 的 Hybrid Flow. 保护MVC客户端: https://www.cnblogs.com/cgzl/ ...
- Identity4实现服务端+api资源控制+客户端请求
准备写一些关于Identity4相关的东西,最近也比较对这方面感兴趣.所有做个开篇笔记记录一下,以便督促自己下一个技术方案方向 已经写好的入门级别Identity4的服务+api资源访问控制和简单的客 ...
随机推荐
- 【mysql】用户和权限管理
1.用户管理 相关命令如下 命令 描述 备注 create user zhang3 identified by '123123'; 创建名称为zhang3 的用户,密码设为123123: sele ...
- git 拉取代码指定分支
问题背景: 新项目还在开发阶段,没有正式对外发布,所以开发同事合并代码到develop上(或者其他名称分支上),而不是到master分支上 通过git拉取代码的时候,默认拉取的是master分支,如下 ...
- Sublime Text3 显示左侧的目录树
file->open folder选择一个文件夹,打开一个新窗口把原来的关掉 View->Sise Bar->Hide Side Bar就可以了
- Android开发,缺少权限导致无法修改原文件,获取所有文件访问权限的方法
在Android 11开发中,app会遇到使用绝对路径无法打开某文件的情况(文件存在根目录下,获取到的路径为:/storage/emulated/0/XXX.txt),而使用相对路径打开文件后(获取到 ...
- Learning to Compare: Relation Network for Few-Shot Learning 论文笔记
主要原理: 和Siamese Neural Networks一样,将分类问题转换成两个输入的相似性问题. 和Siamese Neural Networks不同的是: Relation Network中 ...
- asp语言中if判断语句的求助
If a < 5 Then Response.Redirect("1.asp")ElseIf a > 5 And a < 8 Then Response. ...
- PHP小数点后保留位数并四舍五入
ceil() 函数向上舍入为最接近的整数,进一(k>0).ceil(0.60) --> 1ceil(0.40) --> 1ceil(5) --> 5ceil(5.1) --&g ...
- Kickstart无人值守原理及简介
原文转自:https://www.cnblogs.com/itzgr/p/10029461.html作者:木二 目录 一 简介及原理 二 搭建无人值守步骤 三 PXE介绍 四 Kickstart简介 ...
- 速查列表:Apache SkyWalking OAL 的 域(Scopes)
OAL简介 在流模式(Streaming mode)下,SkyWalking 提供了 观测分析语言(Observability Analysis Language,OAL) 来分析流入的数据. OAL ...
- leetcode 位运算异或
1. 只出现一次的数字(136) 异或的性质总结: 相异为1,相同为0: a ^ a = 0; 0 ^ a = a; 如果 a ^ b = c 成立,那么a ^ c = b 与 b ^ c = a 均 ...