使用密码保护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. 初探Spring Security

    Spring Security 简介 Spring Security是Spring家族中的一个组成框架,具有强大且高度可定制的身份验证和访问控制功能,致力于为Java应用程序提供身份的验证和授权 (先 ...

  2. CentOS7中apache的部署与配置

    一.apache的部署 输入命令 yum list | grep httpd 查看可安装的软件包,选择"httpd.x86_64"安装. 输入命令 yum install http ...

  3. 简析时序数据库 InfluxDB

    时序数据基础 时序数据特点 时序数据TimeSeries是一连串随时间推移而发生变化的相关事件. 以下图的 CPU 监控数据为例,同个 IP 的相关监控数据组成了一条时序数据,不相关数据则分布在不同的 ...

  4. sychronized

    说一下 synchronized 底层实现原理? synchronized可以保证方法或者代码块在运行时, 同一时刻只有一个方法可以进入到临界区, 同时它还可以保证共享变量的内存可见性. Java中每 ...

  5. 闭包 panic recover

    闭包=函数+外层变量的引用 recover必须搭配defer使用 defer一定要在可能引发panic的语句之前定义

  6. new Vue({ render: h => h(App), }).$mount('#app')

    这里创建的vue实例没有el属性,而是在实例后面添加了一个$mount('#app')方法. $mount('#app') :手动挂载到id为app的dom中的意思 当Vue实例没有el属性时,则该实 ...

  7. struts2拦截action多种方法

    按照教程写的,运行的时候显示There is no Action mapped for namespace [/] and action name [login!method1] associated ...

  8. ubuntu软件工具推荐

    时间:2019-04-11 记录:PangYuaner 标题:串口调试利器--Minicom配置及使用详解 地址:https://www.cnblogs.com/wonux/p/5897127.htm ...

  9. EternalBlue永恒之蓝渗透测试

    Eternal Blue(永恒之蓝)-ms17-010渗透测试 第一次做的渗透测试,也是第一次去写博客,还望各位师傅多多指正 :) 工具 1.靶机系统 window7 开放445以及139端口 2.k ...

  10. golangHTML标签提取器soup

    什么是soup 类似python中beatifulsoup,用于提取html标签提取,多用于爬虫.它可以很好的处理不规范标记并生成剖析树(parse tree). 它提供简单又常用的导航,搜索以及修改 ...