身份验证基础结构¶

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

术语表

下面是本章中处理的最常见对象的一些定义。

主密码
允许访问和解密存储在QGIS身份验证数据库中的凭证的密码
身份验证数据库
A Master Password 加密的sqlite db:file`qgis auth.db`其中 Authentication Configuration 存储。例如用户/密码、个人证书和密钥、证书颁发机构
身份验证数据库
Authentication Database
身份验证配置
一组身份验证数据取决于 Authentication Method . 例如,基本身份验证方法存储两个用户/密码。
身份验证配置
Authentication Configuration
身份验证方法
用于进行身份验证的特定方法。每个方法都有自己的协议,用于获得经过身份验证的级别。每个方法都实现为在qgis身份验证基础结构初始化期间动态加载的共享库。

QGSAuthManager入口点

这个 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" )

用新的身份验证配置条目填充AuthDB

任何存储的凭证都是 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:

  1. Basic User and password authentication
  2. Identity-Cert Identity certificate authentication
  3. PKI-Paths PKI paths authentication
  4. PKI-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认证基础设施中解决。

使用qgspkibundle管理pki包

包装由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的类文档。

从authdb中删除条目

我们可以从 Authentication Database 使用它 authcfg 具有以下代码段的标识符:

authMgr = QgsAuthManager.instance()
authMgr.removeAuthenticationConfig( "authCfg_Id_to_remove" )

将AuthCfg扩展保留为QGSAuthManager

使用 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。

其他数据提供程序的PKI示例

其他示例可以在上游的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

在这一段中,列出了可用于在自定义接口中集成身份验证基础结构的可用GUI。

选择凭证的GUI

如果有必要选择 Authentication Configuration 从存储在 Authentication DB 它在GUI类“qgsauthconfigselect<qgis.gui.qgsauthconfigselect>中可用。

../../_images/QgsAuthConfigSelect.png

并可用于以下代码段:

# 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

用于管理凭证、权限和访问身份验证实用程序的完整GUI由 QgsAuthEditorWidgets 班级。

../../_images/QgsAuthEditorWidgets.png

并可用于以下代码段:

# create the instance of the QgsAuthEditorWidgets GUI hierarchically linked to
# the widget referred with `parent`
gui = QgsAuthConfigSelect( parent )
gui.show()

在相关的 test

权限编辑器GUI

用于仅管理权限的GUI由'qgsauthoritieseditor<qgis.gui.qgsauthoritieseditor>类管理。

../../_images/QgsAuthAuthoritiesEditor.png

并可用于以下代码段:

# create the instance of the QgsAuthAuthoritiesEditor GUI hierarchically
#  linked to the widget referred with `parent`
gui = QgsAuthAuthoritiesEditor( parent )
gui.show()