为openid connect实现依赖方授权代码流的包
openidcp的Python项目详细描述
打开idcpy
为OpenID连接依赖方实现授权流客户端的包。该包可用于使用授权流获取openid connect令牌,并使用jwks验证它们。客户机已使用keypolt作为openid连接授权提供程序实现。
用法
唯一使用的类是OidcClient
,可以在代码中导入为:
fromopenidcpyimportOidcClient
您需要按如下方式初始化此客户端:
discovery_url='The .well_known discovery endpoint'client_id='The client id assigned to the RP'client_secret='The client secret assigned to RP if the client is private, otherwise None'client=OidcClient(discovery_url=discovery_url,client_id=client_id,client_secret=client_secret)
客户端基本上公开了3个方法,如果按顺序调用,这些方法将完成授权流。第一个调用是创建授权代码url:
response_type='code'# Always `code` for Authorization Flowredirect_uri='uri where the relying party is running'scopes=['openid','email','profile']# Array of requested scopesstate='Some random generated value that is returned in the redirect, prevents csrf'url=client.create_auth_url(response_type=response_type,redirect_uri=redirect_uri,scopes=scopes,state=state)
您需要将应用程序重定向到上面的url。重定向将导致显示身份验证服务器的登录页。用户登录后,浏览器将重定向到通过授权代码传入上述调用的redirect_uri
。您需要与jwt令牌交换代码,如下所示:
url='redirect_uri + query params, basically the endpoint on which the auth server redirected'redirect_uri='uri where the relying party is running'scopes=['openid','email','profile']# Array of requested scopesstate='Same value from the previous request'tokens=client.get_tokens_from_code(url=url,redirect_uri=redirect_uri,scopes=scopes,state=state)
现在,根据您使用的范围,tokens
字典可以有access_token
、id_token
或两者都有。
下一步是验证这些令牌,客户端提供以下方法:
id_token=tokens['id_token']claims=client.validate_jwt(id_token)
该方法验证令牌的签名、访问群体(是否为您准备令牌)和令牌的过期时间。
claims
字典将包含令牌的解码内容。根据您指定的作用域,它可以包含email
或preferred_username
。
外部依赖性
- 请求(2.20.0)
- Python何塞(3.0.1)
贡献
我们强烈鼓励您做出贡献,因为这只是授权的一个基本实现,而且这里还可以添加很多openid connect。我会尽量增加其余的每当我找到时间,但如果我不能,请随时添加它自己。