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() {
}
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 {
let parameters = [
"refresh_token": refreshToken,
]
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
completion(.retry)
} else {
completion(.doNotRetry)
}
case .failure:
completion(.doNotRetry)
}
}
} else {
completion(.doNotRetry)
}
}
}
- 키체인 관리(reflash token)
import KeychainSwift
let keychain = KeychainSwift()
keychain.set("my_refresh_token", forKey: "com.example.myapp.refreshToken")
if let refreshToken = keychain.get("com.example.myapp.refreshToken") {
print("Refresh token: \(refreshToken)")
} else {
print("Refresh token not found")
}
keychain.delete("com.example.myapp.refreshToken")
- alamofire manager을 만들고 사용
class AlamofireManager {
static let shared = AlamofireManager()
private var sessionManager: Session
private init() {
let retrier = OAuth2Handler()
sessionManager = Session(interceptor: retrier)
let accessToken = retrier.accessToken
let accessTokenAdapter = AccessTokenAdapter(accessToken: accessToken)
sessionManager.adapter = accessTokenAdapter
}
}