使用密码保护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 中文文档与实战

IdentityServer4 知多少

jessetalk视频教程

IdentityServer4[4]使用密码保护API资源的更多相关文章

  1. IdentityServer4 中文文档 -10- (快速入门)使用密码保护API

    IdentityServer4 中文文档 -10- (快速入门)使用密码保护API 原文:http://docs.identityserver.io/en/release/quickstarts/2_ ...

  2. 【IdentityServer4文档】- 使用密码保护 API

    使用密码保护 API OAuth 2.0 协议允许资源拥有者给客户端密码授权:客户端向令牌服务发送用户密码,以获取代表该用户的访问令牌. 该规范建议仅将“资源所有者密码授予”用于“可信”(或旧版)应用 ...

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

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

  4. asp.net core系列 55 IS4使用Identity密码保护API

    一.概述 OAuth 2.0资源(web api)所有者密码授权,允许客户端(Client项目)向令牌服务(IdentityServer项目)发送用户名和密码,并获取代表该用户的访问令牌.在官方文档中 ...

  5. asp.net core系列 55 IS4结合Identity密码保护API

    一.概述 OAuth 2.资源所有者密码授权允许客户端(Client项目)向令牌服务(IdentityServer项目)发送用户名和密码,并获取代表该用户的访问令牌.本篇将IS4结合asp.net c ...

  6. Identity Server 4 - Hybrid Flow - 保护API资源

    这个系列文章介绍的是Identity Server 4 的 Hybrid Flow, 前两篇文章介绍了如何保护MVC客户端, 本文介绍如何保护API资源. 保护MVC客户端的文章: https://w ...

  7. 基于IdentityServer4的单点登录——Api

    1.新建项目并添加引用 新建一个asp .net core 2.0的项目引用IdentityServer4.AccessTokenValidation 2.配置 将Api与IdentityServer ...

  8. Identity Server 4 - Hybrid Flow - 使用ABAC保护MVC客户端和API资源

    这个系列文章介绍的是Identity Server 4 实施 OpenID Connect 的 Hybrid Flow. 保护MVC客户端: https://www.cnblogs.com/cgzl/ ...

  9. Identity4实现服务端+api资源控制+客户端请求

    准备写一些关于Identity4相关的东西,最近也比较对这方面感兴趣.所有做个开篇笔记记录一下,以便督促自己下一个技术方案方向 已经写好的入门级别Identity4的服务+api资源访问控制和简单的客 ...

随机推荐

  1. mysql 优化面试题

    第一方面:30种mysql优化sql语句查询的方法 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by涉及的列上建立索引. 2.应尽量避免在 where 子句中使用 ...

  2. WPF---数据绑定之ValidationRule数据校验综合Demo(七)

     一.概述 我们利用ValidationRule以及ErrorTemplate来制作一个简单的表单验证. 二.Demo 核心思想:我们在ValidationRule中的Validate函数中进行验证, ...

  3. 输入npm install 报错node-sass@4.13.0 postinstall:`node scripts/build.js` Failed at the node-sass@4.13.0

    这个是因为sass安装时获取源的问题,先修改sass安装的源,再运行npm install就成功了 npm config set sass_binary_site=https://npm.taobao ...

  4. 使用Visual Studio分析dump

    最近系统是不是CPU会飙升的百分之九十多甚至百分百,在本地又很难复现问题,无法定位问题出现在哪. 可以用转储文件来保存现场,然后通过分析dump文件可以大概分析出问题的所在 生成转存文件 在CPU飙升 ...

  5. 程序挂了之后别再跟我说让我帮你重启啦! 让supervisor帮你搞定...

    目录 有啥用? 安装 生成配置文件 启动supervisor 自定义配置文件 控制命令 求关注啦 有啥用? 很多我们项目排期进入联调.测试阶段,如果QA同学是直接跟你要一个后端环境的话,那简单点大概率 ...

  6. java交互Scanner类

    用next方法接收 import java.util.Scanner; public class Demo01 { public static void main(String[] args) { / ...

  7. Windows内核-7-IRP和派遣函数

    Windows内核-7-IRP和派遣函数 IRP以及派遣函数是Windows中非常重要的概念.IRP 是I/O Request Pocket的简称,意思是I/O操作的请求包,Windows中所有Use ...

  8. 微信小程序基础知识笔记

    微信小程序笔记 文件构成 全局文件 app.json 小程序全局配置文件,必要,自动生成 app.js 小程序入口JS文件,一般只需申明全局变量.处理生命周期以及版本升级即可,必要 app.wxss ...

  9. Python习题集(七)

    每天一习题,提升Python不是问题!!有更简洁的写法请评论告知我! https://www.cnblogs.com/poloyy/category/1676599.html 题目 如果有一个列表a= ...

  10. Delphi使用Zxing创建二维码

    效果 DelphiZXingQRCode下载地址:https://www.debenu.com/open-source/delphizxingqrcode/ 为了调用方便unit DelphiZXIn ...