OAuth 2.0 and JWT Authorization in Swift: A Step-by-Step Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to OAuth 2.0 and JWT in Swift

\n\n

Modern mobile and desktop applications rarely do without authentication. Two key protocols — OAuth 2.0 and JWT (JSON Web Token) — have become the de facto standard for secure data transfer between client and server. In this article, we will break down how to implement OAuth 2.0 and JWT authorization in Swift for iOS and macOS platforms. You will learn how to set up the token retrieval flow, store them in Keychain, and automatically refresh them upon expiration.

\n\n

The article is intended for beginner developers who are already familiar with the basics of Swift and SwiftUI. We will use URLSession for network requests and Keychain for secure data storage. The code is written in Swift 5.9 and is compatible with iOS 15+ / macOS 12+.

\n\n

What are OAuth 2.0 and JWT?

\n\n

Before writing code, let's understand the theory.

\n\n

OAuth 2.0

\n

OAuth 2.0 is an authorization protocol that allows an application to obtain limited access to a user's resources without transmitting their login and password. Instead, access tokens are used. The main participants are:

\n
    \n
  • Resource Owner — the user.
  • \n
  • Client — your application.
  • \n
  • Authorization Server — the server that issues tokens.
  • \n
  • Resource Server — the API that provides data.
  • \n
\n\n

The most popular flow for mobile applications is Authorization Code Flow with PKCE (Proof Key for Code Exchange). It is secure even without a client secret, which is difficult to store in an application.

\n\n

JWT (JSON Web Token)

\n

JWT is a compact and self-contained token format that contains JSON data. It consists of three parts separated by dots:

\n
    \n
  • Header — the token type and signing algorithm.
  • \n
  • Payload — the useful data (claims), such as user ID, role, expiration time.
  • \n
  • Signature — a signature to verify integrity.
  • \n
\n\n

JWT is often used as an access token in OAuth 2.0. It allows the server to verify the authenticity of a request without querying the database.

\n\n

Practical Implementation in Swift

\n\n

We will create a simple class AuthService that will manage authentication. For the example, we will use the server https://api.example.com.

\n\n

Step 1: Obtaining Tokens via OAuth 2.0

\n\n

First, let's implement a method to obtain tokens using an authorization code. Assume we have already received the authorizationCode through a web view (e.g., ASWebAuthenticationSession).

\n\n
import Foundation\n\nfinal class AuthService {\n    static let shared = AuthService()\n    private let baseURL = "https://api.example.com"\n    private let clientID = "your_client_id"\n    private let redirectURI = "yourapp://callback"\n    \n    // MARK: - Token Retrieval\n    func exchangeCodeForTokens(code: String, codeVerifier: String) async throws -> TokenResponse {\n        let url = URL(string: "\\(baseURL)/oauth/token")!\n        var request = URLRequest(url: url)\n        request.httpMethod = "POST"\n        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")\n        \n        let body = [\n            "grant_type": "authorization_code",\n            "code": code,\n            "redirect_uri": redirectURI,\n            "client_id": clientID,\n            "code_verifier": codeVerifier\n        ]\n        .map { "\\($0.key)=\\($0.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")" }\n        .joined(separator: "&")\n        .data(using: .utf8)\n        \n        request.httpBody = body\n        \n        let (data, response) = try await URLSession.shared.data(for: request)\n        \n        guard let httpResponse = response as? HTTPURLResponse,                

Blogs

Book Recommendations