Перейти к содержанию

CLASS

AuthorizationSession

public class AuthorizationSession : Codable

Client-side refresh-token authorization

After establishing authorisation session establish(_:) keeps refreshing both access and refresh tokens on demand. In case of refresh token expiration throws and is no longer functional until a new session is established.

For multiple parallel sessions one should provide distinct tokenId(s) yet stable for every session (e.g. device ID etc.)

Note

does not perform periodic refresh while idle, so the session would inevitably expire if not called long enough. One may, however periodically call refresh() method

Methods

init(url:tokenId:permissions:)

public init(url: String, tokenId: String, permissions: [String])

Example

 let auth = AuthorizationSession(url: "https://api-cloud-dev.spatium.io/authorization/v1", tokenId: UUID().uuidString, permissions: ["read", "secret"])

 let data = try await jsonPost(
     "https://api-cloud-dev.spatium.io/authorization/v1/api/security-factor/credentials",
     [
         "request-id" : UUID().uuidString
     ],
     CredentialsRequest(
         username: "mario",
         password: "123456"
     ),
     CredentialsResponse.self
 )

 try await auth.establish([data.data.securityToken]);

 let first = try await auth.getPermissionToken();

 try await Task.sleep(nanoseconds: 2_000_000_000)

 try await auth.refresh();

 let second = try await auth.getPermissionToken();

 XCTAssertFalse(first == second)

Parameters

Name Description
url authorisation service endpoint (HTTP(S))
tokenId authorisation session ID, controls multiple parallel sessions
permissions list of required permissions for this session

establish(_:)

public func establish(_ securityTokens: [String]) async throws

Establish a new authorisation session, replacing the previous one, if any.

This method performs initial token acquisition, and may be called once again (with valid tokens) to invalidate a previous refresh token. Before session establishment no token operation may be performed.

Parameters

Name Description
securityTokens a list of gathered security tokens, sufficient to ascuire required permissions

refresh()

public func refresh() async throws

Manually refresh session

Ths method is called internally as required, throws if refresh token is already expired.

getPermissionToken()

public func getPermissionToken() async throws -> String

Get current permission (access) token

As long as refresh token is not expired this method always returns a valid access token, refreshing it if necessary.

Returns

String

permission token as per constructor parameters