How can I get the encrypted password in the auth-manager with PyQGIS?
Asked Answered
S

2

6

I'm making a QGIS plugin in which I ask the for authentication object (with QgsProcessingParameterAuthConfig) for the PostgreSQL connection (which is already set in the connecions list of the user). My goal is to take the login and password with PyQGIS and use these to connect with psycopg2.

The asked parameter QgsProcessingParameterAuthConfig returns a string with the identification key of the authentication object.

  • I can get the QgsAuthMethodConfig object with this key but the password is empty.
  • I didn't found a method to access the password, nor other plugin doing that.
  • It is possible to know the SQLite database where the password is saved, but the are encrypted and I don't know the method to decrypt them.
Sharitasharity answered 6/6, 2019 at 8:27 Comment(0)
U
8

So it seems like you do the following with the string (id):

# get the config id as a string
auth_method_id = self.parameterAsString(
        parameters,
        self.AUTH_CONFIG,
        context
    )

# get the application's authenticaion manager
auth_mgr = QgsApplication.authManager()

# create an empty authmethodconfig object
auth_cfg = QgsAuthMethodConfig()

# load config from manager to the new config instance and decrypt sensitive data
auth_mgr.loadAuthenticationConfig(auth_method_id, auth_cfg, True)

# get the configuration information (including username and password)
auth_cfg.configMap()

I got this from various places in documentation:

https://qgis.org/pyqgis/master/core/QgsAuthManager.html

https://qgis.org/pyqgis/master/core/QgsAuthMethodConfig.html

https://qgis.org/pyqgis/master/core/QgsProcessingParameterAuthConfig.html

Ultraconservative answered 12/11, 2019 at 19:22 Comment(0)
B
0

Minor addition to isamson's helpful response above:

  • You will need to add QgsApplication, QgsAuthManager, QgsAuthMethodConfig to your from qgis.core import call, if not already there.

  • You will want to assign that last object to a variable, which you can then pull credentials out of:

auth_info = auth_cfg.configMap()
try:
    user = auth_info['username']
    password = auth_info['password']
Benton answered 7/6, 2022 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.