使用QWebEngine登录SAML授权页面,等待cookie,然后清除/退出

2024-10-01 19:17:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个PyQT QWebEngineView,它打开一个网站,对AAD进行SAML登录,返回,一旦它看到一个特定的cookie(openconnect webvpn cookie),就会获取该值并将其返回到“控制台”脚本,该脚本可以继续处理和/或返回到命令提示符

我已经将足够多的代码粘在一起,可以弹出一个浏览器窗口,逐步通过SAML授权,查看cookie和cookie值。我不知道如何自动关闭/退出WebView窗口,并将cookie值和/或数组“返回”到Python本身,以便继续处理和/或退出。也不太清楚如何“清理”我的对象

我可能确实伪造了我的类、启动器和对象变量。这是一个难题

想法?想法

这是ArchLinux,通过包repo提供了最新的Python和pyqt

守则:

#!/usr/bin/python

#core python
import sys

#PyQT libraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtNetwork import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

#functions / classes
class OpenconnectSamlAuth(QMainWindow):
   #init self object
   def __init__(self):
      #inherit parents functions, classes, etc....
      super(OpenconnectSamlAuth, self).__init__()

      #create webview object
      self.webview = QWebEngineView()

      #grab profile
      self.profile = QWebEngineProfile("storage", self.webview)
      self.cookie_store = self.profile.cookieStore()
      self.cookie_store.cookieAdded.connect(self.onCookieAdded)

      #empty array of cookies
      self.samlcookies = []

      #set some window options
      #window width x height
      self.resize(1024, 768);

      #default settings
      self.mySettings = QWebEngineSettings.defaultSettings()
      self.mySettings.setAttribute(QWebEngineSettings.JavascriptEnabled, True)


   #load URL / process login
   def samlLogin(self,url):
      #create page and load URL
      webpage = QWebEnginePage(self.profile, self.webview)
      self.webview.setPage(webpage)
      self.webview.load(QUrl(url))

      #windows options
      self.setCentralWidget(self.webview)

      #window title
      self.webview.setWindowTitle('Loading...')
      self.webview.titleChanged.connect(self.updateTitle)


   #update title window       
   def updateTitle(self):
      self.webview.setWindowTitle(self.webview.title())


   #handle cookies being added
   def onCookieAdded(self, cookie):
      #check if cookies exists
      #for c in self.cookies:
      #   if c.hasSameIdentifier(cookie):
      #      return
      #self.cookies.append(QNetworkCookie(cookie))      return;
      #bytearray(c.name()).decode()
      print(bytearray( QNetworkCookie(cookie).name() ).decode() )
      print(bytearray( QNetworkCookie(cookie).value() ).decode() )
      return
         

#main loop
def main():
   #initialize QT application object
   App = QApplication(sys.argv)

   #setup webkit window / browser session
   OpenconnectWebObj = OpenconnectSamlAuth()

   #load URL
   OpenconnectWebObj.samlLogin("https://vpnserverurl/groupname")

   #show connection window
   OpenconnectWebObj.show()

   #execute the app and grab the returned cookie
   cookie = App.exec_()
   print(cookie)

   #exit
   sys.exit()


#if called via command line; run this
if __name__ == '__main__':
   main()

Tags: fromimportselfifmaincookiedefsys
1条回答
网友
1楼 · 发布于 2024-10-01 19:17:31

如果要关闭窗口,则必须调用close()方法,但在本例中,似乎需要终止Qt eventloop,因此应使用QCoreApplication.quit()方法。另一方面,cookie可以存储为属性,然后使用:

import sys

from PyQt5.QtCore import QCoreApplication, QUrl
from PyQt5.QtNetwork import QNetworkCookie
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import (
    QWebEnginePage,
    QWebEngineProfile,
    QWebEngineSettings,
    QWebEngineView,
)


class OpenconnectSamlAuth(QMainWindow):
    def __init__(self, parent=None):
        super(OpenconnectSamlAuth, self).__init__(parent)

        self._cookie = None

        self.webview = QWebEngineView()

        self.profile = QWebEngineProfile("storage", self.webview)
        self.cookie_store = self.profile.cookieStore()
        self.cookie_store.cookieAdded.connect(self.handle_cookie_added)

        self.profile.settings().setAttribute(QWebEngineSettings.JavascriptEnabled, True)

        webpage = QWebEnginePage(self.profile, self)
        self.webview.setPage(webpage)
        self.webview.titleChanged.connect(self.update_title)

        self.setCentralWidget(self.webview)
        self.resize(1024, 768)

    @property
    def cookie(self):
        return self._cookie

    def login(self, url):
        self.webview.load(QUrl.fromUserInput(url))
        self.webview.setWindowTitle("Loading...")

    def update_title(self):
        self.webview.setWindowTitle(self.webview.title())

    def handle_cookie_added(self, cookie):
        print("added {name} : {value}".format(name=cookie.name(), value=cookie.value()))
        if cookie.name() == b"name_of_cookie":
            self._cookie = QNetworkCookie(cookie)
            QCoreApplication.quit()


# main loop
def main():
    app = QApplication(sys.argv)

    openconnect_webobj = OpenconnectSamlAuth()
    openconnect_webobj.login("https://vpnserverurl/groupname")
    openconnect_webobj.show()

    ret = app.exec_()

    cookie = openconnect_webobj.cookie
    if cookie is not None:
        print("results:", cookie.name(), cookie.value(), cookie.toRawForm())

    sys.exit(ret)


if __name__ == "__main__":
    main()

相关问题 更多 >

    热门问题