目前正在使用asp.net core 2.0 (主要是web api)做一个项目, 其中一部分功能需要使用js客户端调用python的pandas, 所以需要建立一个python 的 rest api, 我暂时选用了hug, 官网在这: http://www.hug.rest/.

目前项目使用的是identity server 4, 还有一些web api和js client.

项目的早期后台源码: https://github.com/solenovex/asp.net-core-2.0-web-api-boilerplate

下面开始配置identity server 4, 我使用的是windows.

添加ApiResource:

在 authorization server项目中的配置文件添加红色部分, 这部分就是python hug 的 api:

public static IEnumerable<ApiResource> GetApiResources()

{

return new List<ApiResource>

{

new ApiResource(SalesApiSettings.ApiName, SalesApiSettings.ApiDisplayName) {

UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.PreferredUserName, JwtClaimTypes.Email }

},

new ApiResource("purchaseapi", "采购和原料库API") {

UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.PreferredUserName, JwtClaimTypes.Email }

},

new ApiResource("hugapi", "Hug API") {

UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.PreferredUserName, JwtClaimTypes.Email }

}

};

}

修改js Client的配置:

// Sales JavaScript Client

new Client

{

ClientId = SalesApiSettings.ClientId,

ClientName = SalesApiSettings.ClientName,

AllowedGrantTypes = GrantTypes.Implicit,

AllowAccessTokensViaBrowser = true,

AccessTokenLifetime = 60 * 10,

AllowOfflineAccess = true,

RedirectUris =           { $"{Startup.Configuration["MLH:SalesApi:ClientBase"]}/login-callback", $"{Startup.Configuration["MLH:SalesApi:ClientBase"]}/silent-renew.html" },

PostLogoutRedirectUris = { Startup.Configuration["MLH:SalesApi:ClientBase"] },

AllowedCorsOrigins =     { Startup.Configuration["MLH:SalesApi:ClientBase"] },

AlwaysIncludeUserClaimsInIdToken = true,

AllowedScopes =

{

IdentityServerConstants.StandardScopes.OpenId,

IdentityServerConstants.StandardScopes.Profile,

IdentityServerConstants.StandardScopes.Email,

SalesApiSettings.ApiName,

"hugapi"

}

}

修改js客户端的oidc client配置选项:

添加 hugapi, 与authorization server配置对应.

{

authority: 'http://localhost:5000',

client_id: 'sales',

redirect_uri: 'http://localhost:4200/login-callback',

response_type: 'id_token token',

scope: 'openid profile salesapi hugapi email',

post_logout_redirect_uri: 'http://localhost:4200',

silent_redirect_uri: 'http://localhost:4200/silent-renew.html',

automaticSilentRenew: true,

accessTokenExpiringNotificationTime: 4,

// silentRequestTimeout:10000,

userStore: new WebStorageStateStore({ store: window.localStorage })

}

建立Python Hug api

(可选) 安装virtualenv:

pip install virtualenv

然后在某个地方建立一个目录:

mkdir hugapi && cd hugapi

建立虚拟环境:

virtualenv venv

激活虚拟环境:

venv\Scripts\activate

然后大约这样显示:

安装hug:

pip install hug

这时, 参考一下hug的文档. 然后建立一个简单的api. 建立文件main.py:

import hug@hug.get('/home')def root():    return 'Welcome home!'

运行:

hug -f main.py

结果好用:

然后还需要安装这些:

pip install cryptography pyjwt hug_middleware_cors

其中pyjwt是一个可以encode和decode JWT的库, 如果使用RS256算法的话, 还需要安装cryptography.

而hug_middleware_cors是hug的一个跨域访问中间件(因为js客户端和这个api不是在同一个域名下).

添加需要的引用:

import hug

import jwt

import json

import urllib.request

from jwt.algorithms import get_default_algorithms

from hug_middleware_cors import CORSMiddleware

然后正确的做法是通过Authorization Server的discovery endpoint来找到jwks_uri,

identity server 4 的discovery endpoint的地址是:

http://localhost:5000/.well-known/openid-configuration, 里面能找到各种节点和信息:

但我还是直接写死这个jwks_uri吧:

response = urllib.request.urlopen('http://localhost:5000/.well-known/openid-configuration/jwks')
still_json = json.dumps(json.loads(response.read())['keys'][0])

identity server 4的jwks_uri, 里面是public key, 它的结构是这样的:

而我使用jwt库, 的参数只能传入一个证书的json, 也可就是keys[0].

所以上面的最后一行代码显得有点.......

如果使用python-jose这个库会更简单一些, 但是在我windows电脑上总是安装失败, 所以还是凑合用pyjwt吧.

然后让hug api使用cors中间件:

api = hug.API(__name__)
api.http.add_middleware(CORSMiddleware(api))

然后是hug的authentication部分:

def token_verify(token):

token = token.replace('Bearer ', '')

rsa = get_default_algorithms()['RS256']

cert = rsa.from_jwk(still_json)

try:

result = jwt.decode(token, cert, algorithms=['RS256'], audience='hugapi')

print(result)

return result

except jwt.DecodeError:

return False

token_key_authentication = hug.authentication.token(token_verify)

通过rsa.from_jwk(json) 就会得到key (certificate), 然后通过jwt.decode方法可以把token进行验证并decode, 算法是RS256, 这个方法要求如果token里面包含了aud, 那么方法就需要要指定audience, 也就是hugapi.

最后修改api 方法, 加上验证:

@hug.get('/home', requires=token_key_authentication)def root():    return 'Welcome home!'

最后运行 hug api:

hug -f main.py

端口应该是8000.

运行js客户端,登陆, 并调用这个hug api http://localhost:8000/home:

(我的js客户端是angular5的, 这个没法开源, 公司财产, 不过配置oidc-client还是很简单的, 使用)

返回200, 内容是:

看一下hug的log:

token被正确验证并解析了. 所以可以进入root方法了.

其他的python api框架, 都是同样的道理.

可以使用这个例子自行搭建 https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/7_JavaScriptClient

官方还有一个nodejs api的例子: https://github.com/lyphtec/idsvr4-node-jwks

相关文章:

  • 基于OIDC(OpenID Connect)的SSO

  • 学习Identity Server 4的预备知识

  • 使用Identity Server 4建立Authorization Server (1)

  • 使用Identity Server 4建立Authorization Server (2)

  • 使用Identity Server 4建立Authorization Server (3)

  • 使用Identity Server 4建立Authorization Server (4)

  • 使用Identity Server 4建立Authorization Server (5)

  • IdentityServer4(10)- 添加对外部认证的支持之QQ登录

  • spring cloud+.net core搭建微服务架构:Api授权认证(六)

原文地址:https://www.cnblogs.com/cgzl/p/8270677.html


.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com 

用 Identity Server 4 (JWKS 端点和 RS256 算法) 来保护 Python web api相关推荐

  1. 使用SQL Server 2017 Docker容器在.NET Core中进行本地Web API开发

    目录 介绍 先决条件 最好事先知道 假设 动机 跨平台 快速安装 经济有效 不同版本/多个实例 速度 持久性 找到SQL Server 2017镜像并在本地下载它 在没有卷挂载的情况下在本地执行SQ​ ...

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

    这个系列文章介绍的是Identity Server 4 实施 OpenID Connect 的 Hybrid Flow. 保护MVC客户端: Identity Server 4 - Hybrid Fl ...

  3. Abp商业版 - Identity Server模块

    该模块提供了Identity Server的集成和管理功能. 建立在IdentityServer4类库之上. 管理系统中的客户端,身份资源和API资源(Clients, Identity resour ...

  4. Identity Server 4 - Hybrid Flow - Claims

    前一篇 Identity Server 4 - Hybrid Flow - MVC客户端身份验证: https://www.cnblogs.com/cgzl/p/9253667.html Claims ...

  5. Identity Server 4 预备知识 -- OpenID Connect 简介

    我之前的文章简单的介绍了OAuth 2.0 (在这里: 要用Identity Server 4 -- OAuth 2.0 超级简介, 还不是很全. 这篇文章我要介绍一下 OpenID Connect. ...

  6. 要用Identity Server 4 -- OAuth 2.0 超级简介

    OAuth 2.0 简介 OAuth有一些定义: OAuth 2.0是一个委托协议, 它可以让那些控制资源的人允许某个应用以代表他们来访问他们控制的资源, 注意是代表这些人, 而不是假冒或模仿这些人. ...

  7. 学习Identity Server 4的预备知识

    我要使用asp.net core 2.0 web api 搭建一个基础框架并立即应用于一个实际的项目中去.这里需要使用identity server 4 做单点登陆.下面就简单学习一下相关的预备知识. ...

  8. 带有.NET Core App的Identity Server 4

    什么是Identity Server? Identity Server 4(IdS4)是用于.NET Core应用程序的OpenID Connect和OAuth 2.0框架.它是一种身份验证服务,可为 ...

  9. 使用Identity Server 4建立Authorization Server (2)

    第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一个简单的Identity Server. 接下来继续: 建立Web Api项目 ...

最新文章

  1. Flex+fluorineFx +ASP.NET开发的IIS部署
  2. python学多久可以接单-零基础小白多久能学会python
  3. UVA11997求前k个和,多路归并问题
  4. oracle中表截断是什么意思,Oracle截断表
  5. uva 10934—— Dropping water balloons
  6. SCCM2012 R2集成WSUS服务器-4:部署软件更新组
  7. 自适应图片大小的弹出窗口(3 中方法)
  8. Linux 实用命令
  9. 全国省市区表完整版(自己整理)
  10. Pojo、Po、Vo、Dto的含义
  11. ps中如何批量修改图片
  12. 又有黑科技啦,让老照片还原成彩色!ColouriseSG深度学习上色工具
  13. 火狐怎么打开html页面,电脑如何设置火狐浏览器主页|电脑设置火狐启动页面的方法...
  14. Qt Quick 如何入门?
  15. TensorFlow性能分析调研
  16. JS图片360度全景预览插件
  17. Android 12 变更及适配攻略
  18. tess4j验证码识别
  19. Swift内存布局以及HandyJSON
  20. 让javac在中文系统上输出英文的信息

热门文章

  1. jquery文档加载完毕后执行的几种写法
  2. Spring Boot 入门小目标 3 --- 先来试着热部署
  3. 适配器模式和装饰模式
  4. webpake-node-sass 报错
  5. 【Android】7.1 布局控件常用的公共属性
  6. 解决scrollViewDidScroll do not work的方法
  7. jQuery formValidator表单验证插件4.1.0 下载 演示 文档 可换肤 代码生成器
  8. 去除代码行号的一个小程序(控制台版本)
  9. Blazor University (6)组件 — 组件事件
  10. Xamarin效果第五篇之ScrollView动态滚动效果