refreshToken관리

성민·2023년 7월 28일
0

swift

목록 보기
6/6
import Alamofire

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String

    init(accessToken: String) {
        self.accessToken = accessToken
    }

    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var urlRequest = urlRequest
        urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        completion(.success(urlRequest))
    }
}

class OAuth2Handler: RequestInterceptor {
    private let sessionManager: Session = Session()
    private var accessToken: String = ""
    private var refreshToken: String = ""

    init() {
        // Load access token and refresh token from storage...
    }

    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        let accessTokenAdapter = AccessTokenAdapter(accessToken: accessToken)
        accessTokenAdapter.adapt(urlRequest, for: session, completion: completion)
    }

    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
            // Refresh access token
            let parameters = [
                "refresh_token": refreshToken,
                // Other parameters...
            ]
            sessionManager.request("https://example.com/oauth2/token", method: .post, parameters: parameters).validate().responseJSON { [weak self] response in
                switch response.result {
                case .success(let json):
                    if let json = json as? [String: Any], let accessToken = json["access_token"] as? String, let refreshToken = json["refresh_token"] as? String {
                        self?.accessToken = accessToken
                        self?.refreshToken = refreshToken
                        // Save access token and refresh token to storage...
                        completion(.retry)
                    } else {
                        completion(.doNotRetry)
                    }
                case .failure:
                    completion(.doNotRetry)
                }
            }
        } else {
            completion(.doNotRetry)
        }
    }
}
  1. 키체인 관리(reflash token)
  • KeychainSwift 라이브러리로 관리
import KeychainSwift

let keychain = KeychainSwift()

// Save refresh token to Keychain
keychain.set("my_refresh_token", forKey: "com.example.myapp.refreshToken")

// Load refresh token from Keychain
if let refreshToken = keychain.get("com.example.myapp.refreshToken") {
    print("Refresh token: \(refreshToken)")
} else {
    print("Refresh token not found")
}

// Delete refresh token from Keychain
keychain.delete("com.example.myapp.refreshToken")
  1. alamofire manager을 만들고 사용
class AlamofireManager {
    
	static let shared = AlamofireManager()
    
	private var sessionManager: Session
    
    private init() {
        let retrier = OAuth2Handler()
        sessionManager = Session(interceptor: retrier)

        // Add AccessTokenAdapter to Session
        let accessToken = retrier.accessToken
        let accessTokenAdapter = AccessTokenAdapter(accessToken: accessToken)
        sessionManager.adapter = accessTokenAdapter
    }
}


0개의 댓글