Docs in progress for 'QGIS testing'. Visit https://docs.qgis.org/3.4 for QGIS 3.4 docs and translations.
警告
Despite our constant efforts, information beyond this line may not be updated for QGIS 3. Refer to https://qgis.org/pyqgis/master for the python API documentation or, give a hand to update the chapters you know about. Thanks.
身份验证基础结构的用户参考可以在 认证系统概述 段落。
本章从开发人员的角度描述使用认证系统的最佳实践。
以下大部分代码片段都是从geoserver explorer插件及其测试的代码派生而来的。这是第一个使用身份验证基础结构的插件。在这里可以找到插件代码及其测试 link . 可以从身份验证基础结构中读取其他良好的代码引用 tests code
下面是本章中处理的最常见对象的一些定义。
这个 QgsAuthManager
singleton是使用存储在qgis加密的凭证的入口点。 Authentication DB ,即 qgis-auth.db
文件位于活动项下 user profile 文件夹。
这个类负责用户交互:通过请求设置主密码或透明地使用主密码访问加密的存储信息。
下面的代码段给出了一个设置主密码以打开对身份验证设置的访问的示例。代码注释对于理解代码段很重要。
authMgr = QgsAuthManager.instance()
# check if QgsAuthManager has been already initialized... a side effect
# of the QgsAuthManager.init() is that AuthDbPath is set.
# QgsAuthManager.init() is executed during QGIS application init and hence
# you do not normally need to call it directly.
if authMgr.authenticationDbPath():
# already initilised => we are inside a QGIS app.
if authMgr.masterPasswordIsSet():
msg = 'Authentication master password not recognized'
assert authMgr.masterPasswordSame( "your master password" ), msg
else:
msg = 'Master password could not be set'
# The verify parameter check if the hash of the password was
# already saved in the authentication db
assert authMgr.setMasterPassword( "your master password",
verify=True), msg
else:
# outside qgis, e.g. in a testing environment => setup env var before
# db init
os.environ['QGIS_AUTH_DB_DIR_PATH'] = "/path/where/located/qgis-auth.db"
msg = 'Master password could not be set'
assert authMgr.setMasterPassword("your master password", True), msg
authMgr.init( "/path/where/located/qgis-auth.db" )
任何存储的凭证都是 Authentication Configuration 实例 QgsAuthMethodConfig
使用类似以下字符串的唯一字符串访问的类::
authcfg = 'fm1s770'
该字符串在使用qgis api或gui创建条目时自动生成。
QgsAuthMethodConfig
is the base class
for any Authentication Method.
Any Authentication Method sets a configuration hash map where authentication
informations will be stored. Hereafter an useful snippet to store PKI-path
credentials for an hypothetic alice user:
authMgr = QgsAuthManager.instance()
# set alice PKI data
p_config = QgsAuthMethodConfig()
p_config.setName("alice")
p_config.setMethod("PKI-Paths")
p_config.setUri("https://example.com")
p_config.setConfig("certpath", "path/to/alice-cert.pem" ))
p_config.setConfig("keypath", "path/to/alice-key.pem" ))
# check if method parameters are correctly set
assert p_config.isValid()
# register alice data in authdb returning the ``authcfg`` of the stored
# configuration
authMgr.storeAuthenticationConfig(p_config)
newAuthCfgId = p_config.id()
assert (newAuthCfgId)
Authentication Methods are loaded dynamically during authentication manager init. The list of Authentication method can vary with QGIS evolution, but the original list of available methods is:
Basic
User and password authenticationIdentity-Cert
Identity certificate authenticationPKI-Paths
PKI paths authenticationPKI-PKCS#12
PKI PKCS#12 authentication上述字符串用于标识QGIS认证系统中的认证方法。在 Development 描述如何创建一个新的C++ Authentication Method 。
authMgr = QgsAuthManager.instance()
# add authorities
cacerts = QSslCertificate.fromPath( "/path/to/ca_chains.pem" )
assert cacerts is not None
# store CA
authMgr.storeCertAuthorities(cacerts)
# and rebuild CA caches
authMgr.rebuildCaCertsCache()
authMgr.rebuildTrustedCaCertsCache()
警告
由于qt4/openssl接口的限制,更新后的缓存CA仅在一分钟后才向openssl公开。希望能在qt5认证基础设施中解决。
包装由sslcert、sslkey和ca链组成的pki包的便利类是 QgsPkiBundle
班级。以下是获得密码保护的代码片段:
# add alice cert in case of key with pwd
boundle = QgsPkiBundle.fromPemPaths( "/path/to/alice-cert.pem",
"/path/to/alice-key_w-pass.pem",
"unlock_pwd",
"list_of_CAs_to_bundle" )
assert boundle is not None
assert boundle.isValid()
参照 QgsPkiBundle
从包中提取cert/key/cas的类文档。
我们可以从 Authentication Database 使用它 authcfg
具有以下代码段的标识符:
authMgr = QgsAuthManager.instance()
authMgr.removeAuthenticationConfig( "authCfg_Id_to_remove" )
使用 Authentication Config 存储在 Authentication DB 正在用唯一标识符引用它 authcfg
. 展开,意味着将其从标识符转换为一组完整的凭证。使用存储的最佳实践 Authentication Config 是由认证管理器自动管理的。存储配置的常见用途是连接到启用身份验证的服务(如WMS或WFS)或数据库连接。
注解
考虑到并非所有的QGIS数据提供者都与认证基础设施集成在一起。从基类派生的每个身份验证方法 QgsAuthMethod
并支持一组不同的提供者。例如 certIdentity ()
方法支持以下提供程序列表:
In [19]: authM = QgsAuthManager.instance()
In [20]: authM.authMethod("Identity-Cert").supportedDataProviders()
Out[20]: [u'ows', u'wfs', u'wcs', u'wms', u'postgres']
例如,使用存储的凭据访问WMS服务 authcfg = 'fm1s770'
我们只需要使用 authcfg
在数据源URL中,如下代码段所示:
authCfg = 'fm1s770'
quri = QgsDataSourceURI()
quri.setParam("layers", 'usa:states')
quri.setParam("styles", '')
quri.setParam("format", 'image/png')
quri.setParam("crs", 'EPSG:4326')
quri.setParam("dpiMode", '7')
quri.setParam("featureCount", '10')
quri.setParam("authcfg", authCfg) # <---- here my authCfg url parameter
quri.setParam("contextualWMSLegend", '0')
quri.setParam("url", 'https://my_auth_enabled_server_ip/wms')
rlayer = QgsRasterLayer(quri.encodedUri(), 'states', 'wms')
在上面的例子中, wms
供应商将注意扩大 authcfg
设置HTTP连接前带有凭据的URI参数。
警告
开发商必须离开 authcfg
扩展到 QgsAuthManager
以这种方式,他将确保扩张不会太早。
通常是一个uri字符串,使用 QgsDataSourceURI
类,用于按以下方式设置数据源:
rlayer = QgsRasterLayer( quri.uri(False), 'states', 'wms')
注解
这个 False
参数对于避免URI完全扩展 authcfg
URI中存在的ID。
其他示例可以在上游的QGIS测试中直接读取,如test_authmanager_pki-ows_u或test_authmanager_pki-postgres_u。
许多第三方插件使用httplib2创建HTTP连接,而不是与 QgsNetworkAccessManager
及其相关的认证基础设施集成。为了促进这种集成,已经创建了一个助手python函数 NetworkAccessManager
. 可以找到它的代码 here .
此帮助程序类可在以下代码段中使用:
http = NetworkAccessManager(authid="my_authCfg", exception_class=My_FailedRequestError)
try:
response, content = http.request( "my_rest_url" )
except My_FailedRequestError, e:
# Handle exception
pass
在这一段中,列出了可用于在自定义接口中集成身份验证基础结构的可用GUI。
如果有必要选择 Authentication Configuration 从存储在 Authentication DB 它在GUI类“qgsauthconfigselect<qgis.gui.qgsauthconfigselect>中可用。
并可用于以下代码段:
# create the instance of the QgsAuthConfigSelect GUI hierarchically linked to
# the widget referred with `parent`
gui = QgsAuthConfigSelect( parent, "postgres" )
# add the above created gui in a new tab of the interface where the
# GUI has to be integrated
tabGui.insertTab( 1, gui, "Configurations" )
以上示例取自QGIS源 code GUI构造函数的第二个参数是指数据提供程序类型。该参数用于限制兼容 Authentication Method 具有指定提供程序的。
用于管理凭证、权限和访问身份验证实用程序的完整GUI由 QgsAuthEditorWidgets
班级。
并可用于以下代码段:
# create the instance of the QgsAuthEditorWidgets GUI hierarchically linked to
# the widget referred with `parent`
gui = QgsAuthConfigSelect( parent )
gui.show()
在相关的 test