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资源访问控制和简单的客 ...
随机推荐
- C++ leetcode接雨水
双指针算法"接雨水" 链接:https://leetcode-cn.com/problems/trapping-rain-water/ 给定 n 个非负整数表示每个宽度为 1 的柱 ...
- 梦琪小生 【转】【WPF】WPF MVVM 简单实例
1 新建WPF 应用程序WPFMVVMExample 程序结构如下图所示. 2 Model实现 在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细 ...
- Java学习之 多态 Polymorphism
转自:http://www.cnblogs.com/mengdd/archive/2012/12/25/2832288.html 多态的概念 多态==晚绑定. 不要把函数重载理解为多态. 因为多态是一 ...
- JDK1.5新特性之注解
时间:2017-1-2 20:14 --注解的概述 注释是给人看的,而注解是给程序(框架)看的. 在Servlet3.0中可以使用注解来替代配置文件,开发者就不用再写配置文件了,而是写注解 ...
- nginx《一安装》
linux上nginx相关 wget https://nginx.org/download/nginx-1.14.1.tar.gz tar -zxvf nginx-1.14.1.tar.gz ./co ...
- Java实现小程序微信支付
小程序支付流程交互图: 进入小程序,下单,请求下单支付,调用小程序登录API来获取Openid,生成商户订单 // pages/pay/pay.js var app = getApp(); Page( ...
- Oracle存储过程锁表
存储过程: 解决方法如下: 1:查V$DB_OBJECT_CACHE SELECT * FROM V$DB_OBJECT_CACHE WHERE name='CRM_LASTCHGINFO_DAY' ...
- Python3-sqlalchemy-orm 创建关联表带外键并插入数据
#-*-coding:utf-8-*- #__author__ = "logan.xu" import sqlalchemy from sqlalchemy import crea ...
- Tensorflow之TFRecord的原理和使用心得
本文首发于微信公众号「对白的算法屋」 大家好,我是对白. 目前,越来越多的互联网公司内部都有自己的一套框架去训练模型,而模型训练时需要的数据则都保存在分布式文件系统(HDFS)上.Hive作为构建在H ...
- Django分页组件——Paginator
from django.core.paginator import Paginator #导入Paginator objects = ['john','paul','george','ringo',' ...