Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean OAuth2 token #397

Open
cgkronos opened this issue Sep 13, 2022 · 7 comments
Open

Clean OAuth2 token #397

cgkronos opened this issue Sep 13, 2022 · 7 comments

Comments

@cgkronos
Copy link

cgkronos commented Sep 13, 2022

Hello,
In swift I'm calling successfully a callback URL which revoke a token after the user is logout, and right after I call this to enable re-logging

func runOauth(){
    self.loadingLabel.isHidden=true
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    appDelegate.oauth2!.logger = OAuth2DebugLogger(.debug)
    
    //code executed when OAuth have finished
    appDelegate.oauth2!.afterAuthorizeOrFail = self.callBackOAuth
    

    var url:URL?
    do{
        //the url for authorizing the user, kronos://oauth/callback" is called after the OAuth finish
        url = try appDelegate.oauth2!.authorizeURL(withRedirect:"kronos://oauth/callback", scope: "auth",params: ["tg":"addon/kronos/main","idx":"login.OAuth","formId":"iOS"])
        do{
            let authorizer = appDelegate.oauth2!.authorizer as! OAuth2Authorizer
            //launch OAuth in embeded view "SafariVC"
            print("Safari embeded")
            safariVC = try authorizer.authorizeSafariEmbedded(from: self,at: url!)
            
        }catch let error {
            DispatchQueue.main.async {
                print("ERROR authorizing\(error)")
                //self.runOauth()
            }
        }
    }catch let error {
        DispatchQueue.main.async {
            print("ERROR creating OAuth URL \(error)")
            //self.runOauth()
        }
    }
}

But it re-log the user automatically when loading logging page (I see briefly safariVC but it is dismissed almost instantly), strangely the first logoff works well but if I relog I cannot sign off anymore and I have that line in the console when it relog
[Debug] OAuth2: Did exchange code for access [true] and refresh [true] tokens
In DB the previous token is deleted at the revocation and a new one is created, so I don't know how the user can be relogged without crendentials asked

@cgkronos
Copy link
Author

I've tried

           let appDelegate = UIApplication.shared.delegate as! AppDelegate
           appDelegate.oauth2?.forgetClient()
           appDelegate.oauth2 = OAuth2CodeGrant(settings: OAuthParams  )
           appDelegate.oauth2!.authConfig.authorizeContext = KronosWebsite?.window//KronosWebsite the WKWebview
           runOauth()

and I've this in the console

[Debug] OAuth2: Forgetting client credentials and removing them from keychain
[Warn!] OAuth2: Failed to delete credentials from keychain: Error Domain=swift.keychain.error Code=-25300 "(null)"

@ObscureBug
Copy link
Contributor

I'm no expert at this and haven't used forgetClient(), but I use these as some sites drop a cookie (you can print out the cookies to check whether it's this):

oauth2.forgetTokens()

HTTPCookieStorage.shared.cookies?.forEach() { HTTPCookieStorage.shared.deleteCookie($0) }
_ = WKWebsiteDataStore.default().httpCookieStore		// Flush the cache

btw. You can lookup error codes like -25300 at https://osstatus.com/search/results?platform=all&framework=all&search=-25300

@cgkronos
Copy link
Author

cgkronos commented Sep 14, 2022

Thanks for your answer, but cleaning cookie before runoauth does not seem to fix the issue, I will continue to dig

EDIT:
now the previous errors are gone
I don't know why the OAuth process restart without requiring user credentials, in the console I see this

[Debug] OAuth2: Handling redirect URL kronos://oauth/callback?code=0d8308c0e3b89d79d2109ecbf385a7100c9bd8c9&state=7757EC5E
[Debug] OAuth2: Adding “client_id” and “client_secret” to request body
[Debug] OAuth2: Exchanging code 0d8308c0e3b89d79d2109ecbf385a7100c9bd8c9 for access token at ***
[Debug] OAuth2: Did exchange code for access [true] and refresh [true] tokens

It seems that some infos are stored somewhere but I don't know where

EDIT2:
I've also added this

            let secItemClasses = [kSecClassGenericPassword,
                kSecClassInternetPassword,
                kSecClassCertificate,
                kSecClassKey,
                kSecClassIdentity]
            for secItemClass in secItemClasses {
                let dictionary = [kSecClass as String:secItemClass]
                SecItemDelete(dictionary as CFDictionary)
            }

@cgkronos
Copy link
Author

I've found attributes keychainAccountForClientCredentials and keychainAccountForTokens,
maybe I need to delete data from these account, is this possible and if it is how?

@ObscureBug
Copy link
Contributor

I'm not sure about the attributes you just listed (I do override keychainServiceName and assureCorrectBearerType) but I went through similar debugging to get things going in my case. The things I did was set breakpoints and do some debugging in the OAuth2 library, call oauth2.forgetTokens() and remove the cookies, then restart my app without going through the auth code, and most importantly use the system Keychain Access utility to monitor what is going into the keychain.

Be sure to let us know what you learn.

@cgkronos
Copy link
Author

Ok I've opened the keychain-2-debug.db removed the entries in genp table with a name contain our app id and logoff again and I'm still reconnected immediately. I will double check if this issue truely come from swift app and not from server side, what I'm sure is that the revoking of access_token works (the DB is correctly updated)

@cgkronos
Copy link
Author

cgkronos commented Sep 15, 2022

I've solved this issue, I just had to clean cookies for the SFSafariViewController (I've done that in PHP)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants