{"id":19773154,"url":"https://github.com/ibm-cloud-security/appid-serversdk-swift","last_synced_at":"2025-04-30T18:31:35.010Z","repository":{"id":48979788,"uuid":"82079025","full_name":"ibm-cloud-security/appid-serversdk-swift","owner":"ibm-cloud-security","description":"Swift server SDK for the IBM Cloud App ID service","archived":false,"fork":false,"pushed_at":"2021-06-03T13:52:16.000Z","size":354,"stargazers_count":5,"open_issues_count":2,"forks_count":13,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-10-30T17:14:47.560Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ibm-cloud-security.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-02-15T16:05:20.000Z","updated_at":"2020-11-30T03:28:19.000Z","dependencies_parsed_at":"2022-08-26T12:50:22.796Z","dependency_job_id":null,"html_url":"https://github.com/ibm-cloud-security/appid-serversdk-swift","commit_stats":null,"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibm-cloud-security%2Fappid-serversdk-swift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibm-cloud-security%2Fappid-serversdk-swift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibm-cloud-security%2Fappid-serversdk-swift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ibm-cloud-security%2Fappid-serversdk-swift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ibm-cloud-security","download_url":"https://codeload.github.com/ibm-cloud-security/appid-serversdk-swift/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224219621,"owners_count":17275477,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-12T05:08:49.476Z","updated_at":"2024-11-12T05:08:49.930Z","avatar_url":"https://github.com/ibm-cloud-security.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# IBM Cloud App ID\nSwift SDK for the IBM Cloud App ID service\n\n[![IBM Cloud powered][img-ibmcloud-powered]][url-ibmcloud]\n[![Travis][img-travis-master]][url-travis-master]\n[![Coveralls][img-coveralls-master]][url-coveralls-master]\n[![Codacy][img-codacy]][url-codacy]\n[![Version][img-version]][url-repo]\n[![DownloadsMonthly][img-downloads-monthly]][url-repo]\n[![DownloadsTotal][img-downloads-total]][url-repo]\n[![License][img-license]][url-repo]\n\n[![GithubWatch][img-github-watchers]][url-github-watchers]\n[![GithubStars][img-github-stars]][url-github-stars]\n[![GithubForks][img-github-forks]][url-github-forks]\n\n### Table of Contents\n* [Summary](#summary)\n* [Requirements](#requirements)\n* [Installation](#installation)\n* [Example Usage](#example-usage)\n* [License](#license)\n\n### Summary\n\nThis SDK provides Kitura Credentials plugins for protecting Web applications and API endpoints.\n\nWhen using WebAppKituraCredentialsPlugin the unauthenticated client will get HTTP 302 redirect to the login page hosted by App ID service (or, depending on configuration, directly to identity provider login page).\n\nRead the [official documentation](https://console.bluemix.net/docs/services/appid/protecting-resources.html#requesting-swift) for information about getting started with IBM Cloud App ID Service.\n\n### Requirements\n* Swift +4.2\n* Kitura 2.3\n* OpenSSL\n\n### Installation\n```swift\nimport PackageDescription\n\nlet package = Package(\n    ...\n    dependencies: [\n        .package(url: \"https://github.com/ibm-cloud-security/appid-serversdk-swift.git\", .upToNextMinor(from: \"5.1.0\"))\n    ]\n    .target(\n        name: \"\u003cYour Target\u003e\",\n        dependencies: [\"IBMCloudAppID\"]\n    )\n)\n```\n* 5.1.x releases were tested on OSX and Linux with Swift 5.0 and 4.2\n* 4.1.x releases were tested on OSX and Linux with Swift 4.1.0\n* 4.0.x releases were tested on OSX and Linux with Swift 4.0.3\n* 2.0.x releases were tested on OSX and Linux with Swift 4.0\n* 1.0.x releases were tested on OSX and Linux with Swift 3.1 and 3.1.1\n* 0.0.x releases were tested on OSX and Linux with Swift 3.0.2\n\n### Example Usage\nBelow is an example of using this SDK to protect Web applications.\n\n#### Protecting web applications using WebAppKituraCredentialsPlugin\nWebAppKituraCredentialsPlugin is based on the OAuth2 authorization_code grant flow and should be used for web applications that use browsers. The plugin provides tools to easily implement authentication and authorization flows. WebAppKituraCredentialsPlugin provides mechanisms to detect unauthenticated attempts to access protected resources. The WebAppKituraCredentialsPlugin will automatically redirect user's browser to the authentication page. After successful authentication user will be taken back to the web application's callback URL (redirectUri), which will once again use WebAppKituraCredentialsPlugin to obtain access and identity tokens from App ID service. After obtaining these tokens the WebAppKituraCredentialsPlugin will store them in HTTP session under WebAppKituraCredentialsPlugin.AuthContext key. In a scalable cloud environment it is recommended to persist HTTP sessions in a scalable storage like Redis to ensure they're available across  multiple server app instances.\n\n```swift\nimport Kitura\nimport KituraSession\nimport Credentials\nimport SwiftyJSON\nimport IBMCloudAppID\n\n// Below URLs will be used for App ID OAuth flows\nvar LOGIN_URL = \"/ibm/bluemix/appid/login\"\nvar CALLBACK_URL = \"/ibm/bluemix/appid/callback\"\nvar LOGOUT_URL = \"/ibm/bluemix/appid/logout\"\nvar LANDING_PAGE_URL = \"/index.html\"\n\n// Setup Kitura to use session middleware\n// Must be configured with proper session storage for production\n// environments. See https://github.com/IBM-Swift/Kitura-Session for\n// additional documentation\nlet router = Router()\nlet session = Session(secret: \"Some secret\")\nrouter.all(middleware: session)\n\n// Use static resources if required directory\nrouter.all(\"/\", middleware: StaticFileServer(path: \"./Tests/IBMCloudAppIDTests/public\"))\n\n// Below configuration can be obtained from Service Credentials\n// tab in the App ID Dashboard. You're not required to manually provide below\n// configuration if your Kitura application runs on IBM Cloud and is bound to the\n// App ID service instance. In this case App ID configuration will be obtained\n// automatically using VCAP_SERVICES environment variable.\n//\n// The redirectUri value can be supplied in three ways:\n// 1. Manually in new WebAppKituraCredentialsPlugin options\n// 2. As environment variable named `redirectUri`\n// 3. If none of the above was supplied the App ID SDK will try to retrieve\n//    application_uri of the application running on IBM Cloud and append a\n//    default suffix \"/ibm/bluemix/appid/callback\"\nlet options = [\n\t\"clientId\": \"{client-id}\",\n\t\"secret\": \"{secret}\",\n\t\"tenantId\": \"{tenant-id}\",\n\t\"oauthServerUrl\": \"{oauth-server-url}\",\n\t\"redirectUri\": \"{app-url}\" + CALLBACK_URL\n]\nlet webappKituraCredentialsPlugin = WebAppKituraCredentialsPlugin(options: options)\nlet kituraCredentials = Credentials()\nkituraCredentials.register(plugin: webappKituraCredentialsPlugin)\n\n// Explicit login endpoint\nrouter.get(LOGIN_URL,\n\t\t   handler: kituraCredentials.authenticate(credentialsType: webappKituraCredentialsPlugin.name,\n\t\t\t\t\t\t\t\t\t\t\t\t   successRedirect: LANDING_PAGE_URL,\n\t\t\t\t\t\t\t\t\t\t\t\t   failureRedirect: LANDING_PAGE_URL\n))\n\n// Callback to finish the authorization process. Will retrieve access and identity tokens from App ID\nrouter.get(CALLBACK_URL,\n\t\t   handler: kituraCredentials.authenticate(credentialsType: webappKituraCredentialsPlugin.name,\n\t\t\t\t\t\t\t\t\t\t\t\t   successRedirect: LANDING_PAGE_URL,\n\t\t\t\t\t\t\t\t\t\t\t\t   failureRedirect: LANDING_PAGE_URL\n))\n\n// Logout endpoint. Clears authentication information from session\nrouter.get(LOGOUT_URL, handler:  { (request, response, next) in\n\tkituraCredentials.logOut(request: request)\n\twebappKituraCredentialsPlugin.logout(request: request)\n\t_ = try? response.redirect(LANDING_PAGE_URL)\n})\n\n// Protected area  using `Credentials` standard `userProfile`\nrouter.get(\"/protected\", handler: kituraCredentials.authenticate(credentialsType: webappKituraCredentialsPlugin.name), { (request, response, next) in\n    // check user profile for successful login\n    guard let user = request.userProfile else {\n        response.status(.unauthorized)\n        return next()\n    }\n    try response.send(\"Hello \\(user.displayName)\")\n    next()\n})\n\n// Protected area using AppID `userIdentity`\nrouter.get(\"/protected\", handler: kituraCredentials.authenticate(credentialsType: webappKituraCredentialsPlugin.name), { (request, response, next) in\n    guard let authContextDict = request.session?[\"APPID_AUTH_CONTEXT\"] as? [String: Any],\n          let identityTokenPayload = authContextDict[\"identityTokenPayload\"] as? [String: Any],\n          let identityTokenData = try? JSONSerialization.data(withJSONObject: identityTokenPayload, options: [])\n    else {\n        response.status(.unauthorized)\n        return next()\n    }\n    let authContext = AuthorizationContext(idTokenPayload: JSON(data: identityTokenData))\n    response.send(\"Hello \\(authContext.userIdentity.displayName)\")\n    next()\n})\n\n// Start the server!\nKitura.addHTTPServer(onPort: 1234, with: router)\nKitura.run()\n\n\n```\n\n#### Protecting API endpoints using APIKituraCredentialsPlugin\n\nThe APIKituraCredentialsPlugin follows the OAuth Bearer Token spec and should be used to protect backend API endpoints.\n\nWhen your Kitura backend receives a request, the credentials middleware will check for the existence of a Bearer token in its authorization header and then validate it against an App ID public key set. Upon success, the middleware will add the authorization context and user profile to the request and pass it to the next middleware or your handler. If an identity token is not provided, then the fields of the user profile will be empty.\n\n```swift\nimport Kitura\nimport Credentials\nimport IBMCloudAppID\n\n// Below configuration can be obtained from Service Credentials\n// tab in the App ID Dashboard. You're not required to manually provide below\n// configuration if your Kitura application runs on IBM Cloud and is bound to the\n// App ID service instance. In this case App ID configuration will be obtained\n// automatically using VCAP_SERVICES environment variable.\nlet options = [\n\t\"oauthServerUrl\": \"{oauth-server-url}\"\n]\n\nlet apiCredentials = APIKituraCredentialsPlugin(options: options)\nlet credentials = Credentials()\ncredentials.register(plugin: apiCredentials)\n\n\n// Protected area\nrouter.all(middleware: credentials)\nrouter.get(\"/myName\") { (request, response, next) in\n\n\n    do {\n        if let userProfile = request.userProfile  {\n            try response.status(.OK).send(userProfile.displayName).end()\n        }\n    } catch {\n        response.status(.internalServerError)\n    }\n}\n\n// Start the server!\nKitura.addHTTPServer(onPort: 8080, with: router)\nKitura.run()\n```\n\n#### Anonymous login\nWebAppKituraCredentialsPlugin allows users to login to your web application anonymously, meaning without requiring any credentials. After successful login the anonymous user access token will be persisted in HTTP session, making it available as long as HTTP session is kept alive. Once HTTP session is destroyed or expired the anonymous user access token will be destroyed as well.  \n\nTo allow anonymous login for a particular URL use two configuration properties as shown on a code snippet below:\n* `WebAppKituraCredentialsPlugin.AllowAnonymousLogin` - set this value to true if you want to allow your users to login anonymously when accessing this endpoint. If this property is set to true no authentication will be required. The default value of this property is `false`, therefore you must set it explicitly to allow anonymous login.\n* `WebAppKituraCredentialsPlugin.AllowCreateNewAnonymousUser` - By default a new anonymous user will be created every time this method is invoked unless there's an existing anonymous access_token stored in the current HTTP session. In some cases you want to explicitly control whether you want to automatically create new anonymous user or not. Set this property to `false` if you want to disable automatic creation of new anonymous users. The default value of this property is `true`.  \n\n```swift\nvar LOGIN_ANON_URL = \"/ibm/bluemix/appid/loginanon\"\n\nlet webappKituraCredentialsPlugin = WebAppKituraCredentialsPlugin(options: options)\nlet kituraCredentialsAnonymous = Credentials(options: [\n\tWebAppKituraCredentialsPlugin.AllowAnonymousLogin: true,\n\tWebAppKituraCredentialsPlugin.AllowCreateNewAnonymousUser: true\n])\nkituraCredentialsAnonymous.register(plugin: webappKituraCredentialsPlugin)\n\n// Explicit anonymous login endpoint\nrouter.get(LOGIN_ANON_URL,\n\t\t   handler: kituraCredentialsAnonymous.authenticate(credentialsType: webappKituraCredentialsPlugin.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccessRedirect: LANDING_PAGE_URL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfailureRedirect: LANDING_PAGE_URL\n))\n\n\nrouter.get(LOGOUT_URL, handler:  { (request, response, next) in\n\tkituraCredentialsAnonymous.logOut(request: request)\n\twebappKituraCredentialsPlugin.logout(request: request)\n\t_ = try? response.redirect(LANDING_PAGE_URL)\n})\n\n```\n\nThe anonymous access token and identity token are automatically persisted in HTTP session by App ID SDK. You can retrieve them from HTTP session via same mechanisms as regular tokens. Access and identity tokens will be kept in HTTP session and will be used until the tokens or the HTTP session expires.\n\n### Managing User Profiles\n\nUsing the App ID UserProfileManager, you are able to create, delete, and retrieve user profile attributes as well as get additional info about a user.\n\n```swift\n\nlet userProfileManager = UserProfileManager(options: options)\n\nuserProfileManager.getAttribute(accessToken: accessToken, attributeName: \"name\") { (err, res) in\n}\n\nuserProfileManager.setAttribute(accessToken: accessToken, attributeName: \"name\", attributeValue : \"abc\") { (err, res) in\n}\n\nuserProfileManager.getAllAttributes(accessToken: accessToken) { (err, res) in\n}\n\nuserProfileManager.deleteAllAttributes(accessToken: accessToken) { (err, res) in\n}\n\n// Retrieve user information by querying the UserInfo endpoint\n// If identity token is provided (recommended approach), response is validated against the identity token\nuserProfileManager.getUserInfo(accessToken: accessToken, identityToken: optionalIdentityToken) { (err, res) in\n\n}\n\n// Retrieve the UserInfo without any validation\nuserProfileManager.getUserInfo(accessToken: accessToken) { (err, res) in\n\n}\n```\n\n### License\nThis package contains code licensed under the Apache License, Version 2.0 (the \"License\"). You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 and may also view the License in the LICENSE file within this package.\n\n[img-ibmcloud-powered]: https://img.shields.io/badge/ibm%20cloud-powered-blue.svg\n[url-ibmcloud]: https://www.ibm.com/cloud/\n[url-repo]: https://github.com/ibm-cloud-security/appid-serversdk-swift\n[img-license]: https://img.shields.io/github/license/ibm-cloud-security/appid-serversdk-swift.svg\n[img-version]: https://img.shields.io/github/release/ibm-cloud-security/appid-serversdk-swift.svg\n[img-downloads-monthly]: https://img.shields.io/github/downloads/ibm-cloud-security/appid-serversdk-swift/latest/total.svg\n[img-downloads-total]: https://img.shields.io/github/downloads/ibm-cloud-security/appid-serversdk-swift/total.svg\n\n[img-github-watchers]: https://img.shields.io/github/watchers/ibm-cloud-security/appid-serversdk-swift.svg?style=social\u0026label=Watch\n[url-github-watchers]: https://github.com/ibm-cloud-security/appid-serversdk-swift/watchers\n[img-github-stars]: https://img.shields.io/github/stars/ibm-cloud-security/appid-serversdk-swift.svg?style=social\u0026label=Star\n[url-github-stars]: https://github.com/ibm-cloud-security/appid-serversdk-swift/stargazers\n[img-github-forks]: https://img.shields.io/github/forks/ibm-cloud-security/appid-serversdk-swift.svg?style=social\u0026label=Fork\n[url-github-forks]: https://github.com/ibm-cloud-security/appid-serversdk-swift/network\n\n[img-travis-master]: https://travis-ci.org/ibm-cloud-security/appid-serversdk-swift.svg\n[url-travis-master]: https://travis-ci.org/ibm-cloud-security/appid-serversdk-swift\n\n[img-coveralls-master]: https://coveralls.io/repos/github/ibm-cloud-security/appid-serversdk-swift/badge.svg\n[url-coveralls-master]: https://coveralls.io/github/ibm-cloud-security/appid-serversdk-swift\n\n[img-codacy]: https://api.codacy.com/project/badge/Grade/a6952171ff5c4adaa6cf41a8652516d4?branch=master\n[url-codacy]: https://www.codacy.com/app/ibm-cloud-security/appid-serversdk-swift\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fibm-cloud-security%2Fappid-serversdk-swift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fibm-cloud-security%2Fappid-serversdk-swift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fibm-cloud-security%2Fappid-serversdk-swift/lists"}