Search code examples
swiftmacosswiftuiwebkit

Authentication Process with SwiftUI on macOS


I want to authenticate my user with Spotify for a Spotify client in SwiftUI now I've come to the problem that it seems like Webkit doesn't work on macOS and now I have no clue how to authenticate my user via Safari (or some other Browser).

It would be really helpful if somebody could help me and maybe have a solution and an explanation for that solution.

Thanks.


Solution

  • Take a look at the ASWebAuthenticationSession class. This class simplifies logging into websites by creating a private browser window for people to log into a website. By using ASWebAuthenticationSession, you don't have to deal with WebKit.

    To use ASWebAuthenticationSession you must perform the following steps:

    • Create a custom URL type for your app to take you back to your app when someone finishes logging in.
    • Create a class for the login session that conforms to ASWebAuthenticationPresentationContextProviding.
    • Add a presentation anchor for the login session.
    • Create an instance of ASWebAuthenticationSession, supplying the URL of the site you want to log in, the URL to go to when the session finishes, and a completion handler with code to run when the session ends successfully.

    The following article has more details on working with ASWebAuthenticationSession:

    Log in to Websites with ASWebAuthenticationSession