認証インフラストラクチャ¶
警告
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.
前書き¶
認証基盤のユーザーリファレンスはユーザーマニュアル中で 認証システムの概要 段落を参照して下さい。
この章では、開発者の観点から、認証システムを使用するベストプラクティスについて説明します。
Most of the following snippets are derived from the code of Geoserver Explorer plugin and its tests. This is the first plugin that used Authentication infrastructure. The plugin code and its tests can be found at this link. Other good code reference can be read from the authentication infrastructure tests code.
用語集¶
これはこの章で扱われる最も一般的なオブジェクトのいくつかの定義です。
- マスターパスワード
アクセスを許可し、QGIS認証DBに保存された資格情報を復号化するパスワードです
- 認証データベース
A Master Password crypted sqlite db
qgis-auth.db
where Authentication Configuration are stored. e.g user/password, personal certificates and keys, Certificate Authorities- 認証DB
- 認証の設定
認証データの構成は 認証メソッド によって異なります。例えばベーシック認証の場合は、ユーザー/パスワードの対が格納されます。
- 認証config
認証設定
- 認証方法
認証されるためには特別な方法が利用されています。各方法は、認証されるためにそれぞれ独自のプロトコルを利用しています。それぞれの方法は共有ライブラリとしてQGIS認証基盤の初期化中に動的にロードされるように実装されています。
エントリポイントQgsAuthManager¶
The QgsAuthManager
singleton
is the entry point to use the credentials stored in the QGIS encrypted
Authentication DB, i.e. the qgis-auth.db
file under the
active user profile folder.
このクラスは、ユーザーの操作に対応します:マスターパスワードを設定するか、または暗号化されて保存された情報に透過的アクセスするかを尋ねます。
マネージャを初期化し、マスターパスワードを設定する¶
次のコード例は、認証設定へのアクセスを開くために、マスターパスワードを設定する例を示します。コードのコメントは、このコード例を理解するために重要です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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" )
|
認証データベースに新しい認証構成項目を設定する¶
Any stored credential is a Authentication Configuration instance of the
QgsAuthMethodConfig
class accessed using a unique string like the following one:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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)
|
利用可能な認証方法¶
認証メソッド群は認証マネージャ初期化中に動的にロードされます。認証方法のリストは、QGISの進化によって変わることがありますが、使用可能なメソッドの元のリストは以下のとおりです:
Basic
ユーザーとパスワード認証Identity-Cert
アイデンティティ証明書認証PKI-Paths
PKIパス認証PKI-PKCS#12
PKI PKCS#12認証
上記の文字列はQGIS認証システムにおける認証方法を識別するものです。 開発 セクションでは、新しいC ++ 認証メソッドを作成する方法を説明しています。
認証局の導入¶
1 2 3 4 5 6 7 8 9 | 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に1分後に公開されます。これはQT5認証インフラストラクチャで解決されることを願っています。
QgsPkiBundleでPKIバンドルを管理する¶
A convenience class to pack PKI bundles composed on SslCert, SslKey and CA
chain is the QgsPkiBundle
class. Hereafter a snippet to get password protected:
1 2 3 4 5 6 7 | # 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()
|
Refer to QgsPkiBundle
class documentation
to extract cert/key/CAs from the bundle.
認証データベースからエントリを削除する¶
以下が 認証データベース からエントリをその authcfg
識別子を使用して削除するコード例です:
authMgr = QgsAuthManager.instance()
authMgr.removeAuthenticationConfig( "authCfg_Id_to_remove" )
QgsAuthManagerにauthcfg展開を残す¶
The best way to use an Authentication Config stored in the
Authentication DB is referring it with the unique identifier
authcfg
. Expanding, means convert it from an identifier to a complete
set of credentials.
The best practice to use stored Authentication Configs, is to leave it
managed automatically by the Authentication manager.
The common use of a stored configuration is to connect to an authentication
enabled service like a WMS or WFS or to a DB connection.
注釈
Take into account that not all QGIS data providers are integrated with the
Authentication infrastructure. Each authentication method, derived from the
base class QgsAuthMethod
and support a different set of Providers. For example the certIdentity ()
method supports the following list
of providers:
In [19]: authM = QgsAuthManager.instance()
In [20]: authM.authMethod("Identity-Cert").supportedDataProviders()
Out[20]: ['ows', 'wfs', 'wcs', 'wms', 'postgres']
例えば、 authcfg = 'fm1s770'
で識別保存された資格情報を使用してWMSサービスにアクセスするためには、次のコードのように、データ・ソースのURLに authcfg
を使用する必要があります。
1 2 3 4 5 6 7 8 9 10 11 12 | 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
プロバイダーは、単にHTTP接続を設定する前に、資格を authcfg
URIパラメーターを拡張するために世話をします。
警告
The developer would have to leave authcfg
expansion to the QgsAuthManager
, in this way he will be sure that expansion is not done too early.
Usually an URI string, built using the QgsDataSourceURI
class, is used to set a data source in the following way:
rlayer = QgsRasterLayer( quri.uri(False), 'states', 'wms')
注釈
False
パラメーターは、URIで authcfg
IDの存在のURI完全な展開を避けるために重要です。
他のデータプロバイダーとPKIの例¶
Other example can be read directly in the QGIS tests upstream as in test_authmanager_pki_ows or test_authmanager_pki_postgres.
認証インフラストラクチャを使用するようにプラグインを適応させる¶
Many third party plugins are using httplib2 to create HTTP connections instead
of integrating with QgsNetworkAccessManager
and its related Authentication Infrastructure integration.
To facilitate this integration an helper python function has been created
called NetworkAccessManager
. Its code can be found here.
このヘルパークラスは、次のコードのように使用できます:
1 2 3 4 5 6 | 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¶
If it's necessary to select a Authentication Configuration from the set stored in the Authentication DB it is available in the GUI class QgsAuthConfigSelect <qgis.gui.QgsAuthConfigSelect>.
そして次のコードのように使用できます:
1 2 3 4 5 6 | # 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" )
|
The above example is taken from the QGIS source code The second parameter of the GUI constructor refers to data provider type. The parameter is used to restrict the compatible Authentication Methods with the specified provider.
認証エディタのGUI¶
The complete GUI used to manage credentials, authorities and to access to
Authentication utilities is managed by the
QgsAuthEditorWidgets
class.
そして次のコードのように使用できます:
# create the instance of the QgsAuthEditorWidgets GUI hierarchically linked to
# the widget referred with `parent`
gui = QgsAuthConfigSelect( parent )
gui.show()
an integrated example can be found in the related test.
認証局エディタのGUI¶
A GUI used to manage only authorities is managed by the QgsAuthAuthoritiesEditor <qgis.gui.QgsAuthAuthoritiesEditor> class.
そして次のコードのように使用できます:
# create the instance of the QgsAuthAuthoritiesEditor GUI hierarchically
# linked to the widget referred with `parent`
gui = QgsAuthAuthoritiesEditor( parent )
gui.show()