How to detect redirected url in swift aswebsession?

Viewed 11

I have a oauth link that redirects me to a different page (redirect_uri) after entering the user's credentials. The URL of the redirected page has the authorization code. How can I get the link of the second page so I can extract the code from it? I have tried callbackURL however, that didn't work. Thank you in advance!

import Foundation
import AuthenticationServices
import CryptoKit



public func UrlGenerator() -> URL {
    func randomString(length: Int) -> String {
      let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
      return String((0..<length).map{ _ in letters.randomElement()! })
    }
    let code_verifier = randomString(length: 86)
    let hashdata = Data(code_verifier.utf8)
    let code_challenge_data = SHA256.hash(data: hashdata)
    let code_challenge_generated = code_challenge_data.compactMap { String(format: "%02x", $0) }.joined()

    let url = "https://auth.tesla.com/oauth2/v3/authorize"
    let client_id = "ownerapi"
    let code_challenge = "\(code_challenge_generated)"
    let code_challenge_method = "S256"
    let redirect_uri = "https://auth.tesla.com/void/callback"
    let response_type = "code"
    let scope = "openid%2Bemail%2Boffline_access"
    let state = "\(code_verifier)"

    let TeslaLink = "\(url)?client_id=\(client_id)&code_challenge=\(code_challenge)&code_challenge_method=\(code_challenge_method)&redirect_uri=\(redirect_uri)&response_type=\(response_type)&scope=\(scope)&state=\(state)"
        let TeslaLinkURL = URL(string: TeslaLink)!
        return TeslaLinkURL
}



class SignInViewModel: NSObject, ObservableObject, ASWebAuthenticationPresentationContextProviding {
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
            return ASPresentationAnchor()
        }
    func TeslaSignIn() {
        let authURL = UrlGenerator()
        let scheme = "TESRIUM"
        let webAuthSession = ASWebAuthenticationSession.init(url: authURL, callbackURLScheme: scheme, completionHandler: { callbackURL, error in
           
                })
        webAuthSession.presentationContextProvider = self
        webAuthSession.prefersEphemeralWebBrowserSession = true
        webAuthSession.start()
            }
        }
0 Answers
Related