How to detect redirected url in swift aswebsession?


This Content is from Stack Overflow. Question asked by BlazeProg

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 = ""
    let client_id = "ownerapi"
    let code_challenge = "(code_challenge_generated)"
    let code_challenge_method = "S256"
    let redirect_uri = ""
    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


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?