Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate urls by using origin in oidc config #151

Merged
merged 2 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Authgear.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
A652CEFA2A8A2C8F006E789F /* Asn1IntegerConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = A652CEF92A8A2C8F006E789F /* Asn1IntegerConversion.swift */; };
A68DAD2229AF686000487DAF /* UILocales.swift in Sources */ = {isa = PBXBuildFile; fileRef = A68DAD1F29AF686000487DAF /* UILocales.swift */; };
A68DAD2929AF688E00487DAF /* String+encodeAsQueryComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = A68DAD2629AF688E00487DAF /* String+encodeAsQueryComponent.swift */; };
A6FCB0A52AF37E4300DAC260 /* URL+origin.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6FCB0A42AF37E4300DAC260 /* URL+origin.swift */; };
F83392EF24FC344D00A69D3C /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = F83392EE24FC344D00A69D3C /* Storage.swift */; };
F83392F124FDA87900A69D3C /* AuthgearError.swift in Sources */ = {isa = PBXBuildFile; fileRef = F83392F024FDA87900A69D3C /* AuthgearError.swift */; };
F83392F324FE38FE00A69D3C /* URLComponents+QueryParames.swift in Sources */ = {isa = PBXBuildFile; fileRef = F83392F224FE38FE00A69D3C /* URLComponents+QueryParames.swift */; };
Expand Down Expand Up @@ -66,6 +67,7 @@
A652CEF92A8A2C8F006E789F /* Asn1IntegerConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Asn1IntegerConversion.swift; sourceTree = "<group>"; };
A68DAD1F29AF686000487DAF /* UILocales.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UILocales.swift; sourceTree = "<group>"; };
A68DAD2629AF688E00487DAF /* String+encodeAsQueryComponent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String+encodeAsQueryComponent.swift"; sourceTree = "<group>"; };
A6FCB0A42AF37E4300DAC260 /* URL+origin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URL+origin.swift"; sourceTree = "<group>"; };
"Authgear::Authgear::Product" /* Authgear.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = Authgear.framework; sourceTree = BUILT_PRODUCTS_DIR; };
"Authgear::AuthgearTests::Product" /* Authgear-iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; path = "Authgear-iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
CC20D6F025BAA3C400E579DD /* Pods.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Pods.xcodeproj; path = example/Pods/Pods.xcodeproj; sourceTree = "<group>"; };
Expand Down Expand Up @@ -179,6 +181,7 @@
F8A657A825055A7C0027888F /* Base64.swift */,
A652CEBA2A822D19006E789F /* Dictionary+encodeAsQuery.swift */,
A68DAD2629AF688E00487DAF /* String+encodeAsQueryComponent.swift */,
A6FCB0A42AF37E4300DAC260 /* URL+origin.swift */,
A68DAD1F29AF686000487DAF /* UILocales.swift */,
);
path = Sources;
Expand Down Expand Up @@ -290,6 +293,7 @@
A652CEFA2A8A2C8F006E789F /* Asn1IntegerConversion.swift in Sources */,
F8A657A925055A7C0027888F /* Base64.swift in Sources */,
F83392F324FE38FE00A69D3C /* URLComponents+QueryParames.swift in Sources */,
A6FCB0A52AF37E4300DAC260 /* URL+origin.swift in Sources */,
775FF72A2603649500B81ECD /* Biometric.swift in Sources */,
775FF73426047C7700B81ECD /* DeviceInfo.swift in Sources */,
F8A657A7250551ED0027888F /* JWT.swift in Sources */,
Expand Down
90 changes: 63 additions & 27 deletions Sources/APIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ struct AppSessionTokenResponse: Decodable {

protocol AuthAPIClient: AnyObject {
var endpoint: URL { get }
func makeAuthgearURL(path: String, handler: @escaping (Result<URL, Error>) -> Void)
func fetchOIDCConfiguration(handler: @escaping (Result<OIDCConfiguration, Error>) -> Void)
func requestOIDCToken(
grantType: GrantType,
Expand Down Expand Up @@ -400,6 +401,21 @@ class DefaultAuthAPIClient: AuthAPIClient {
}
}

func makeAuthgearURL(path: String, handler: @escaping (Result<URL, Error>) -> Void) {
fetchOIDCConfiguration { result in
switch result {
case let .success(config):
guard let authgearOrigin = config.authorizationEndpoint.origin() else {
return handler(.failure(wrapError(error: AuthgearError.runtimeError("invalid authorization_endpoint"))))
}
let resultURL = authgearOrigin.appendingPathComponent(path)
return handler(.success(resultURL))
case let .failure(error):
return handler(.failure(wrapError(error: error)))
}
}
}

func requestOIDCToken(
grantType: GrantType,
clientId: String,
Expand Down Expand Up @@ -576,28 +592,42 @@ class DefaultAuthAPIClient: AuthAPIClient {
purpose: String,
handler: @escaping (Result<ChallengeResponse, Error>) -> Void
) {
var urlRequest = URLRequest(url: endpoint.appendingPathComponent("/oauth2/challenge"))
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.httpBody = try? JSONEncoder().encode(ChallengeBody(purpose: purpose))

fetch(request: urlRequest, handler: { (result: Result<APIResponse<ChallengeResponse>, Error>) in
handler(result.flatMap { $0.toResult() })
})
makeAuthgearURL(path: "/oauth2/challenge") { result in
switch result {
case let .failure(err):
handler(.failure(err))
case let .success(url):
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.httpBody = try? JSONEncoder().encode(ChallengeBody(purpose: purpose))

self.fetch(request: urlRequest, handler: { (result: Result<APIResponse<ChallengeResponse>, Error>) in
handler(result.flatMap { $0.toResult() })
})
}
}
}

func requestAppSessionToken(
refreshToken: String,
handler: @escaping (Result<AppSessionTokenResponse, Error>) -> Void
) {
var urlRequest = URLRequest(url: endpoint.appendingPathComponent("/oauth2/app_session_token"))
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.httpBody = try? JSONEncoder().encode(AppSessionTokenBody(refreshToken: refreshToken))

fetch(request: urlRequest, handler: { (result: Result<APIResponse<AppSessionTokenResponse>, Error>) in
handler(result.flatMap { $0.toResult() })
})
makeAuthgearURL(path: "/oauth2/app_session_token") { result in
switch result {
case let .failure(err):
handler(.failure(err))
case let .success(url):
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.httpBody = try? JSONEncoder().encode(AppSessionTokenBody(refreshToken: refreshToken))

self.fetch(request: urlRequest, handler: { (result: Result<APIResponse<AppSessionTokenResponse>, Error>) in
handler(result.flatMap { $0.toResult() })
})
}
}
}

func requestWechatAuthCallback(code: String, state: String, handler: @escaping (Result<Void, Error>) -> Void) {
Expand All @@ -609,16 +639,22 @@ class DefaultAuthAPIClient: AuthAPIClient {
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems

let u = endpoint.appendingPathComponent("/sso/wechat/callback")
var urlRequest = URLRequest(url: u)
urlRequest.httpMethod = "POST"
urlRequest.setValue(
"application/x-www-form-urlencoded",
forHTTPHeaderField: "content-type"
)
urlRequest.httpBody = urlComponents.query?.data(using: .utf8)
authgearFetch(urlSession: self.defaultSession, request: urlRequest, handler: { result in
handler(result.map { _ in () })
})
makeAuthgearURL(path: "/sso/wechat/callback") { result in
switch result {
case let .failure(err):
handler(.failure(err))
case let .success(url):
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue(
"application/x-www-form-urlencoded",
forHTTPHeaderField: "content-type"
)
urlRequest.httpBody = urlComponents.query?.data(using: .utf8)
authgearFetch(urlSession: self.defaultSession, request: urlRequest, handler: { result in
handler(result.map { _ in () })
})
}
}
}
}
59 changes: 44 additions & 15 deletions Sources/Authgear.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,45 @@ public class Authgear {
}
}

func generateAuthgearURL(
path: String,
uiLocales: [String]? = nil,
colorScheme: ColorScheme? = nil,
handler: URLCompletionHandler?
) {
let handler = handler.map { h in self.withMainQueueHandler(h) }
self.workerQueue.async {
self.apiClient.makeAuthgearURL(path: path) { result in
switch result {
case let .failure(err):
handler?(.failure(err))
case let .success(url):
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)!
var queryItems = urlComponents.queryItems ?? []
if let uiLocales = uiLocales {
queryItems.append(URLQueryItem(
name: "ui_locales",
value: uiLocales.joined(separator: " ")
))
}
if let colorScheme = colorScheme {
queryItems.append(URLQueryItem(name: "x_color_scheme", value: colorScheme.rawValue))
}
urlComponents.queryItems = queryItems
let redirectURI = urlComponents.url!
self.generateURL(redirectURI: redirectURI.absoluteString) { generatedResult in
switch generatedResult {
case let .failure(err):
handler?(.failure(err))
case let .success(url):
handler?(.success(url))
}
}
}
}
}
}

public func openURL(
path: String,
uiLocales: [String]? = nil,
Expand All @@ -1032,21 +1071,11 @@ public class Authgear {
) {
let handler = handler.map { h in withMainQueueHandler(h) }

var urlComponents = URLComponents(url: apiClient.endpoint.appendingPathComponent(path), resolvingAgainstBaseURL: false)!
var queryItems = urlComponents.queryItems ?? []
if let uiLocales = uiLocales {
queryItems.append(URLQueryItem(
name: "ui_locales",
value: uiLocales.joined(separator: " ")
))
}
if let colorScheme = colorScheme {
queryItems.append(URLQueryItem(name: "x_color_scheme", value: colorScheme.rawValue))
}
urlComponents.queryItems = queryItems
let url = urlComponents.url!

self.generateURL(redirectURI: url.absoluteString) { [weak self] result in
self.generateAuthgearURL(
path: path,
uiLocales: uiLocales,
colorScheme: colorScheme
) { [weak self] result in
guard let self = self else { return }

switch result {
Expand Down
15 changes: 15 additions & 0 deletions Sources/URL+origin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Foundation

extension URL {
func origin() -> URL? {
var originURLComponents = URLComponents()
if #available(iOS 16.0, *) {
originURLComponents.host = self.host()
} else {
originURLComponents.host = self.host
}
originURLComponents.scheme = self.scheme
originURLComponents.port = self.port
return originURLComponents.url
}
}