使用 Azure 应用程序身份验证和 Python 连接到 SharePoint

问题描述 投票:0回答:0

我创建了一个自签名证书并将其上传到 Azure 应用程序注册,类似于我对十几个其他应用程序所做的。我正在尝试使用 Python 的 office365 库连接到我的 SharePoint 网站,这不是我有很多经验并且它显示出来的东西。

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file_system_object_type import FileSystemObjectType
import os 

def create_client_with_private_key():

    cert_credentials = {
        'tenant': tenant,
        'client_id': appid,
        'thumbprint': thumb,
        'cert_path': path
    }
    return ClientContext(siteurl).with_client_certificate(**cert_credentials)


siteurl = 'https://mytenant.sharepoint.com/sites/mysite'
appid = '<AppID guid>'
tenant = '<TenantID>'
thumb = '<certificate thumbprint>'
path = "d:\\azure cert\\mycertificate.pem"

ctx = create_client_with_private_key()
current_web = ctx.web.get().execute_query()
print("{0}".format(current_web.url))

在倒数第二行 (

current_web = ctx.web.get().execute_query()
) 出现此错误的脚本

发生异常:ValueError (“无法反序列化密钥数据。数据可能格式不正确,可能使用不支持的算法加密,或者它可能是不支持的密钥类型(例如带有显式参数的 EC 曲线)。”,[_OpenSSLErrorWithText(code= 75497580, lib=9, reason=108, reason_text=b'error:0480006C:PEM routines::no start line')]) ValueError:无法反序列化关键数据。数据的格式可能不正确,或者可能使用不受支持的算法进行了加密。

在处理上述异常的过程中,又出现了一个异常:

文件“C:\scripts\sp-test.py”,第 50 行,位于 current_web = ctx.web.get().execute_query() ValueError: ('无法反序列化密钥数据。数据可能格式不正确,可能使用不支持的算法加密,或者它可能是不支持的密钥类型(例如带有显式参数的 EC 曲线)。', [_OpenSSLErrorWithText( code=75497580, lib=9, reason=108, reason_text=b'error:0480006C:PEM routines::no start line')])

我读过我需要确保安装了 python 加密包,我确实这样做了。我猜证书的格式是错误的,但我不确定我应该把它放在什么格式。

我使用以下 PowerShell 脚本创建证书

$validMonths =12;
$notAfter = (Get-Date).AddMonths($validMonths) # Valid for 4 months
$thumb = (New-SelfSignedCertificate -DnsName "mycertificate" -CertStoreLocation "cert:\LocalMachine\My"  -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $certPassword -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath $certPath -Password $pwd
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate($certPath, $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
New-AzureADApplicationKeyCredential -ObjectId $objectID -Type AsymmetricX509Cert -Usage Verify -Value $keyValue -EndDate ($notAfter.AddHours(-2))

创建一个 pfx 文件。我先试过了,但没用。然后我将证书导出为 pem

Export-Certificate -Type CERT -Cert "cert:\localmachine\my\$thumb" -FilePath "$baseCertPath\$($certName).der"; 
certutil -encode "$baseCertPath\$($certName).der" "$baseCertPath\$($certName).pem";

我做错了什么?

python office365 sharepoint-online
© www.soinside.com 2019 - 2024. All rights reserved.