当前位置:网站首页>Using VBA's WebBrowser control to realize single sign on (SSO) in Excel

Using VBA's WebBrowser control to realize single sign on (SSO) in Excel

2022-06-10 04:03:00 Jin Mu Zatan

demand

Excel You can make a lot of beautiful statements on , The product manager hopes to be able to Excel Login page pops up on , Single sign on ,
After login , Retrieve the template list from the server , Select one of the templates , Insert into Excel in .

Design

  1. The login interface can be realized by front-end technology , such as Angular And VUE
  2. VBA The built-in WebBrowser Control can be loaded as Web Of the login page “ shell ”.
  3. VBA Keep trying to get... On the page cookie, Until you get it cookie, also cookie Contained in the token.
  4. Use URLDecode decode cookie, obtain token.
  5. Use this token issue rest api Request to get a list of templates .

Part of the implementation

from WebBrowser obtain cookie

Public Function GetCookieFromBrowser(serverIP As String)
    Dim url As String
    Dim encodedCookie As String
    
    encodedCookie = ""
    url = "https://" + serverIP + "/test/login/" + "?refresh=" + Guid()

    FLoginWeb.FWebBrowser.Silent = True
    FLoginWeb.FWebBrowser.Navigate url
    FLoginWeb.Show vbModeless
    
    Do Until InStr(FLoginWeb.FWebBrowser.Document.cookie, "token") > 0: DoEvents: Loop
    
    If FLoginWeb.FWebBrowser.Document.cookie <> "" Then
        encodedCookie = FLoginWeb.FWebBrowser.Document.cookie
        FLoginWeb.Hide        
    End If
    GetEncodedCookieFromWebBrowser = encodedCookie
End Function

Be careful

  1. because VBA Of WebBrowser yes IE kernel , Microsoft has officially renounced its support for IE, So with Angular、VUE Etc , There may be WebBrowser The web page cannot be loaded normally , More testing is needed .
  2. WebBrowser The default version used is IE7 Compatibility mode for , For a better experience , You can modify the registry to support IE11, The method is as follows :
Public Sub SetWebBrowserIE11()
    Dim fso
    Dim RegKey_User_IE As String
    Dim oWshell
    Dim excelKey As String
    
    On Error Resume Next
    Set fso = CreateObject("Scripting.FileSystemObject")
    RegKey_User_IE = "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\excel.exe"
    Set oWshell = CreateObject("WScript.Shell")
    excelKey = oWshell.RegRead(RegKey_User_IE)
    If excelKey = "" Then
        oWshell.RegWrite RegKey_User_IE, "11000", "REG_DWORD"
    End If
    Set oWshell = Nothing
End Sub
原网站

版权声明
本文为[Jin Mu Zatan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091344210291.html