浏览代码

Adding new Packages

/main/staging/closed_beta_package_update
当前提交
a5ac6a0d
共有 1051 个文件被更改,包括 2887 次插入0 次删除
  1. 242
      Packages/com.unity.services.authentication/.README - External.md
  2. 7
      Packages/com.unity.services.authentication/CHANGELOG.md.meta
  3. 5
      Packages/com.unity.services.authentication/Documentation~/com.unity.services.authentication.md
  4. 8
      Packages/com.unity.services.authentication/Editor.meta
  5. 7
      Packages/com.unity.services.authentication/LICENSE.md.meta
  6. 7
      Packages/com.unity.services.authentication/README.md.meta
  7. 8
      Packages/com.unity.services.authentication/Runtime.meta
  8. 40
      Packages/com.unity.services.authentication/Third Party Notices.md
  9. 7
      Packages/com.unity.services.authentication/Third Party Notices.md.meta
  10. 7
      Packages/com.unity.services.authentication/package.json.meta
  11. 67
      Packages/com.unity.services.authentication/CHANGELOG.md
  12. 5
      Packages/com.unity.services.authentication/Editor/AssemblyInfo.cs
  13. 3
      Packages/com.unity.services.authentication/Editor/AssemblyInfo.cs.meta
  14. 3
      Packages/com.unity.services.authentication/Editor/AuthenticationAdminClient.cs.meta
  15. 11
      Packages/com.unity.services.authentication/Editor/AuthenticationAdminNetworkClient.cs.meta
  16. 11
      Packages/com.unity.services.authentication/Editor/AuthenticationIdentifier.cs.meta
  17. 47
      Packages/com.unity.services.authentication/Editor/AuthenticationService.cs
  18. 11
      Packages/com.unity.services.authentication/Editor/AuthenticationService.cs.meta
  19. 3
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsElement.cs.meta
  20. 47
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsHelper.cs
  21. 3
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsHelper.cs.meta
  22. 58
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsProvider.cs
  23. 11
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsProvider.cs.meta
  24. 20
      Packages/com.unity.services.authentication/Editor/AuthenticationTopMenu.cs
  25. 11
      Packages/com.unity.services.authentication/Editor/AuthenticationTopMenu.cs.meta
  26. 3
      Packages/com.unity.services.authentication/Editor/IAuthenticationAdminClient.cs.meta
  27. 3
      Packages/com.unity.services.authentication/Editor/IdProviderElement.cs.meta
  28. 8
      Packages/com.unity.services.authentication/Editor/Models.meta
  29. 49
      Packages/com.unity.services.authentication/Editor/Models/CreateIdProviderRequest.cs
  30. 11
      Packages/com.unity.services.authentication/Editor/Models/CreateIdProviderRequest.cs.meta
  31. 20
      Packages/com.unity.services.authentication/Editor/Models/DeleteIdProviderRequest.cs
  32. 11
      Packages/com.unity.services.authentication/Editor/Models/DeleteIdProviderRequest.cs.meta
  33. 19
      Packages/com.unity.services.authentication/Editor/Models/GetIdDomainResponse.cs
  34. 11
      Packages/com.unity.services.authentication/Editor/Models/GetIdDomainResponse.cs.meta
  35. 56
      Packages/com.unity.services.authentication/Editor/Models/IdProviderResponse.cs
  36. 11
      Packages/com.unity.services.authentication/Editor/Models/IdProviderResponse.cs.meta
  37. 19
      Packages/com.unity.services.authentication/Editor/Models/ListIdProviderResponse.cs
  38. 11
      Packages/com.unity.services.authentication/Editor/Models/ListIdProviderResponse.cs.meta
  39. 29
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeErrorResponse.cs
  40. 11
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeErrorResponse.cs.meta
  41. 16
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeRequest.cs
  42. 11
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeRequest.cs.meta
  43. 16
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeResponse.cs
  44. 11
      Packages/com.unity.services.authentication/Editor/Models/TokenExchangeResponse.cs.meta
  45. 44
      Packages/com.unity.services.authentication/Editor/Models/UpdateIdProviderRequest.cs
  46. 11
      Packages/com.unity.services.authentication/Editor/Models/UpdateIdProviderRequest.cs.meta
  47. 3
      Packages/com.unity.services.authentication/Editor/USS.meta
  48. 41
      Packages/com.unity.services.authentication/Editor/USS/AuthenticationStyleSheet.uss
  49. 3
      Packages/com.unity.services.authentication/Editor/USS/AuthenticationStyleSheet.uss.meta
  50. 3
      Packages/com.unity.services.authentication/Editor/UXML.meta
  51. 15
      Packages/com.unity.services.authentication/Editor/UXML/AuthenticationProjectSettings.uxml
  52. 3
      Packages/com.unity.services.authentication/Editor/UXML/AuthenticationProjectSettings.uxml.meta
  53. 12
      Packages/com.unity.services.authentication/Editor/UXML/IdProviderElement.uxml
  54. 3
      Packages/com.unity.services.authentication/Editor/UXML/IdProviderElement.uxml.meta
  55. 10
      Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.api
  56. 7
      Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.api.meta
  57. 23
      Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.asmdef
  58. 7
      Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.asmdef.meta
  59. 294
      Packages/com.unity.services.authentication/Editor/AuthenticationAdminClient.cs
  60. 146
      Packages/com.unity.services.authentication/Editor/AuthenticationAdminNetworkClient.cs
  61. 18
      Packages/com.unity.services.authentication/Editor/AuthenticationIdentifier.cs
  62. 292
      Packages/com.unity.services.authentication/Editor/AuthenticationSettingsElement.cs
  63. 78
      Packages/com.unity.services.authentication/Editor/IAuthenticationAdminClient.cs
  64. 399
      Packages/com.unity.services.authentication/Editor/IdProviderElement.cs
  65. 5
      Packages/com.unity.services.authentication/LICENSE.md
  66. 79
      Packages/com.unity.services.authentication/README.md
  67. 3
      Packages/com.unity.services.authentication/Runtime/AuthenticationAsyncOperation.cs.meta
  68. 58
      Packages/com.unity.services.authentication/Runtime/AuthenticationError.cs
  69. 3
      Packages/com.unity.services.authentication/Runtime/AuthenticationError.cs.meta
  70. 49
      Packages/com.unity.services.authentication/Runtime/AuthenticationException.cs
  71. 3
      Packages/com.unity.services.authentication/Runtime/AuthenticationException.cs.meta
  72. 11
      Packages/com.unity.services.authentication/Runtime/AuthenticationNetworkClient.cs.meta
  73. 11
      Packages/com.unity.services.authentication/Runtime/AuthenticationService.cs.meta
  74. 11
      Packages/com.unity.services.authentication/Runtime/AuthenticationServiceInternal.cs.meta
  75. 48
      Packages/com.unity.services.authentication/Runtime/CodeChallengeGenerator.cs
  76. 11
      Packages/com.unity.services.authentication/Runtime/CodeChallengeGenerator.cs.meta
  77. 8
      Packages/com.unity.services.authentication/Runtime/Core.meta
  78. 11
      Packages/com.unity.services.authentication/Runtime/IAuthenticationService.cs.meta
  79. 11
      Packages/com.unity.services.authentication/Runtime/JwtDecoder.cs.meta
  80. 3
      Packages/com.unity.services.authentication/Runtime/Models.meta
  81. 44
      Packages/com.unity.services.authentication/Runtime/Models/AccessToken.cs
  82. 11
      Packages/com.unity.services.authentication/Runtime/Models/AccessToken.cs.meta
  83. 29
      Packages/com.unity.services.authentication/Runtime/Models/AuthenticationErrorResponse.cs
  84. 11
      Packages/com.unity.services.authentication/Runtime/Models/AuthenticationErrorResponse.cs.meta
  85. 39
      Packages/com.unity.services.authentication/Runtime/Models/BaseJwt.cs
  86. 11
      Packages/com.unity.services.authentication/Runtime/Models/BaseJwt.cs.meta
  87. 19
      Packages/com.unity.services.authentication/Runtime/Models/ExternalTokenRequest.cs
  88. 11
      Packages/com.unity.services.authentication/Runtime/Models/ExternalTokenRequest.cs.meta

242
Packages/com.unity.services.authentication/.README - External.md


# UPM Package Starter Kit
The purpose of this starter kit is to provide the data structure and development guidelines for new packages meant for the **Unity Package Manager (UPM)**.
## Are you ready to become a package?
The Package Manager is a work-in-progress for Unity and, in that sense, there are a few criteria that must be met for your package to be considered on the package list at this time:
- **Your code accesses public Unity C# APIs only.** If you have a native code component, it will need to ship with an official editor release. Internal API access might eventually be possible for Unity made packages, but not at this time.
- **Your code doesn't require security, obfuscation, or conditional access control.** Anyone should be able to download your package and access the source code.
## Package structure
```none
<root>
├── package.json
├── README.md
├── CHANGELOG.md
├── LICENSE.md
├── Third Party Notices.md
├── QAReport.md
├── Editor
│ ├── Unity.[YourPackageName].Editor.asmdef
│ └── EditorExample.cs
├── Runtime
│ ├── Unity.[YourPackageName].asmdef
│ └── RuntimeExample.cs
├── Tests
│ ├── .tests.json
│ ├── Editor
│ │ ├── Unity.[YourPackageName].Editor.Tests.asmdef
│ │ └── EditorExampleTest.cs
│ └── Runtime
│ ├── Unity.[YourPackageName].Tests.asmdef
│ └── RuntimeExampleTest.cs
├── Samples
│ └── Example
│ ├── .sample.json
│ └── SampleExample.cs
└── Documentation~
├── your-package-name.md
└── Images
```
## Develop your package
Package development works best within the Unity Editor. Here's how to set that up:
1. Start **Unity**, create a local empty project.
1. In a console (or terminal) application, go to the newly created project folder, then copy the contents of this starter kit into the packages directory.
__Note:__ Your directory name must be the name of your package (Example: `"com.unity.terrain-builder"`)
1. ##### Fill in your package information
Update the following required fields in file **package.json**:
- `"name"`: Package name, it should follow this naming convention: `"com.[YourCompanyName].[sub-group].[your-package-name]"`
(Example: `"com.unity.2d.animation"`, where `sub-group` should match the sub-group you selected in Gitlab)
- `"displayName"`: Package user friendly display name. (Example: `"Terrain Builder SDK"`). <br>__Note:__ Use a display name that will help users understand what your package is intended for.
- `"version"`: Package version `"X.Y.Z"`, your project **must** adhere to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
Follow this guideline:
- To introduce a new feature or bug fix, increment the minor version (X.**Y**.Z)
- To introduce a breaking API change, increment the major version (**X**.Y.Z)
- The patch version (X.Y.**Z**), is reserved for sustainable engineering use only.
- `"unity"`: Unity Version your package is compatible with. (Example: `"2018.1"`)
- `"description"`: This description appears in the Package Manager window when the user selects this package from the list. For best results, use this text to summarize what the package does and how it can benefit the user.<br>__Note:__ Special formatting characters are supported, including line breaks (`\n`) and unicode characters such as bullets (`\u25AA`).<br>
Update the following recommended fields in file **package.json**:
- `"dependencies"`: List of packages this package depends on. All dependencies will also be downloaded and loaded in a project with your package. Here's an example:
```
dependencies: {
"com.unity.ads": "1.0.0"
"com.unity.analytics": "2.0.0"
}
```
- `"keywords"`: List of words that will be indexed by the package manager search engine to facilitate discovery.
Update the following field in file **Tests/.tests.json**:
- `"createSeparatePackage"`: If this is set to true, the CI will create a separate package for these tests. If you leave it set to false, the tests will remain part of the published package. If you set it to true, the tests in your package will automatically be moved to a separate package, and metadata will be added at publish time to link the packages together. This allows you to have a large number of tests, or assets, etc. that you don't want to include in your main package, while making it easy to test your package with those tests & fixtures.
1. You should now see your package in the Project Window, along with all other available packages for your project.
1. ##### Rename and update assembly definition files.
Assembly definition files are used to generate C# assemblies during compilation. Package code must include asmdef files to ensure package code isolation. You can read up on assembly definition files [here](https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html).
If your package contains Editor code, rename and modify [Editor/Unity.YourPackageName.Editor.asmdef](Editor/Unity.YourPackageName.Editor.asmdef). Otherwise, delete the Editor directory.
* Name **must** match your package name, suffixed by `.Editor` (i.e `Unity.[YourPackageName].Editor`)
* Assembly **must** reference `Unity.[YourPackageName]` (if you have any Runtime)
* Platforms **must** include `"Editor"`
If your package contains code that needs to be included in Unity runtime builds, rename and modify [Runtime/Unity.YourPackageName.asmdef](Runtime/Unity.YourPackageName.asmdef). Otherwise, delete the Runtime directory.
* Name **must** match your package name (i.e `Unity.[YourPackageName]`)
If your package has Editor code, you **must** include Editor Tests in your package. In that case, rename and modify [Tests/Editor/Unity.YourPackageName.Editor.Tests.asmdef](Tests/Editor/Unity.YourPackageName.Editor.Tests.asmdef).
* Name **must** match your package name, suffixed by `.Editor.Tests` (i.e `Unity.[YourPackageName].Editor.Tests`)
* Assembly **must** reference `Unity.[YourPackageName].Editor` and `Unity.[YourPackageName]` (if you have any Runtime)
* Platforms **must** include `"Editor"`
* Optional Unity references **must** include `"TestAssemblies"` to allow your Editor Tests to show up in the Test Runner/run on Katana when your package is listed in project manifest `testables`
If your package has Runtime code, you **must** include Playmode Tests in your package. In that case, rename and modify [Tests/Runtime/Unity.YourPackageName.Tests.asmdef](Tests/Runtime/Unity.YourPackageName.Tests.asmdef).
* Name **must** match your package name, suffixed by `.Tests` (i.e `Unity.[YourPackageName].Tests`)
* Assembly **must** reference `Unity.[YourPackageName]`
* Optional Unity references **must** include `"TestAssemblies"` to allow your Playmode Tests to show up in the Test Runner/run on Katana when your package is listed in project manifest `testables`
>
> The reason for choosing such name schema is to ensure that the name of the assembly built based on *assembly definition file* (_a.k.a .asmdef_) will follow the .Net [Framework Design Guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/index)
1. ##### Document your package.
Rename and update **your-package-name.md** documentation file. Use this documentation template file to create preliminary, high-level documentation. This document is meant to introduce users to the features and sample files included in your package. Your package documentation files will be used to generate online and local docs, available from the package manager UI.
**Document your public APIs**
* All public APIs need to be documented with XmlDoc. If you don't need an API to be accessed by clients, mark it as internal instead.
* API documentation is generated from [XmlDoc tags](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/xml-documentation-comments) included with all public APIs found in the package. See [Editor/EditorExample.cs](Editor/EditorExample.cs) for an example.
**Documentation flow**
* Documentation needs to be ready when a publish request is sent to Release Management, as they will ask the documentation team to review it.
* The package will remain in `preview` mode until the final documentation is completed. Users will have access to the developer-generated documentation only in preview packages.
* When the documentation is completed, the documentation team will update the package git repo with the updates and they will publish it on the web.
* The package's development team will then need to submit a new package version with updated docs.
* The starting page in the user manual that links to package documentation is [Here](https://docs.unity3d.com/Manual/PackagesList.html).
* The `Documentation~` folder is suffixed with `~` so that its content does not get loaded in the editor, which is the recommended behavior. If this is problematic, you can still name it `Documentation` and all tools will still work correctly. `.Documentation` is also supported.
**Test your documentation locally**
As you are developing your documentation, you can see what your documentation will look like by using the DocTools extension (optional).
Once the DocTools package is installed, it will add a `Generate Documentation` button in the Package Manager UI's details of your installed packages. To install the extension, follow these steps:
1. Make sure you have `Package Manager UI v1.9.6` or above.
1. Your project manifest will need to point to a staging registry for this, which you can do by adding this line to it: `"registry": "https://staging-packages.unity.com"`
1. Install `Package Manager DocTools v1.0.0-preview.6` or above from the `Package Manager UI` (in the `All Packages` section).
1. After installation, you will see a `Generate Documentation` button which will generate the documentation locally, and open a web browser to a locally served version of your documentation so you can preview it.
1. (optional) If your package documentation contains multiple `.md` files for the user manual, see [this page](https://docs.unity3d.com/Packages/com.unity.package-manager-doctools@1.0/manual/index.html#table-of-content) to add a table of content to your documentation.
The DocTools extension is still in preview, if you come across arguable results, please discuss them on #docs-packman.
1. ##### Add samples to your package (code & assets).
If your package contains a sample, rename the `Samples/Example` folder, and update the `.sample.json` file in it.
In the case where your package contains multiple samples, you can make a copy of the `Samples/Example` folder for each sample, and update the `.sample.json` file accordingly.
Similar to `.tests.json` file, there is a `"createSeparatePackage"` field in `.sample.json`.If set to true, the CI will create an separate package for the sample..
Delete the `Samples` folder altogether if your package does not need samples.
As of Unity release 2019.1, the /Samples directory of a package will be recognized by the package manager. Samples will not be imported to Unity when the package is added to a project, but will instead be offered to users of the package as an optional import, which can be added to their "/Assets" directory through a UI option.
1. ##### Validate your package.
Before you publish your package, you need to make sure that it passes all the necessary validation checks by using the Package Validation Suite extension (optional).
Once the Validation Suite package is installed, it will add a `Validate` button in the Package Manager UI's details of your installed packages. To install the extension, follow these steps:
1. Make sure you have `Package Manager UI v1.9.6` or above.
1. Your project manifest will need to point to a staging registry for this, which you can do by adding this line to it: `"registry": "https://staging-packages.unity.com"`
1. Install `Package Validation Suite v0.3.0-preview.13` or above from the `Package Manager UI` in the `All Packages` section. If you can't find it there, try turning on `Show preview packages` in the `Advanced` menu.
1. After installation, you will see a `Validate` button show up in the Package Manager UI, which, when pressed, will run a series of tests and expose a `See Results` button for additional explanation.
1. If it succeeds, you will see a green bar with a `Success` message.
1. If it fails, you will see a red bar with a `Failed` message.
The validation suite is still in preview, if you come across arguable results, please discuss them on #release-management.
1. ##### Add tests to your package.
All packages must contain tests. Tests are essential for Unity to ensure that the package works as expected in different scenarios.
**Editor tests**
* Write all your Editor Tests in `Tests/Editor`
**Playmode Tests**
* Write all your Playmode Tests in `Tests/Runtime`.
1. ##### Update **CHANGELOG.md**.
Every new feature or bug fix should have a trace in this file. For more details on the chosen changelog format, see [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
## Create a Pre-Release Package
Pre-Release Packages are a great way of getting your features in front of Unity Developers in order to get early feedback on functionality and UI designs. Pre-Release packages need to go through the publishing to production flow, as would any other package, but with diminished requirements. Here are the supported Pre-Release tags (to be used in package.json,`version` field), along with the requirements for each one:
**Preview** - ex: `"version" : "1.2.0-preview"`
* Expected Package structure respected
* Package loads in Unity Editor without errors
* License file present - With third party notices file if necessary
* Test coverage is good - Optional but preferred
* Public APIs documented, minimal feature docs exists- Optional but preferred
## Make sure your package meets all legal requirements
##### Update **Third Party Notices.md** & **License.md**
1. If your package has third-party elements and its licenses are approved, then all the licenses must be added to the `Third Party Notices.md` file. Simply duplicate the `Component Name/License Type/Provide License Details` section if you have more then one licenes.
a. Concerning `[Provide License Details]` in the `Third Party Notices.md`, a URL can work as long as it actually points to the reproduced license and the copyright information _(if applicable)_.
1. If your package does not have third party elements, you can remove the `Third Party Notices.md` file from your package.
## Preparing your package for Staging
Before publishing your package to production, you must send your package on the Package Manager's **staging** repository. The staging repository is monitored by QA and release management, and is where package validation will take place before it is accepted in production.
## *** IMPORTANT: The staging repository is publicly accessible, do not publish any packages with sensitive material you aren't ready to share with the public ***
1. Publishing your changes to the package manager's **staging** repository happens from Gitlab. To do so, simply setup your project's Continuous integration, which will be triggered by "Tags" on your branches.
* Join the **#devs-packman** channel on Slack, and request a staging **USERNAME** and **API_KEY**.
* In Gitlab, under the **Settings-> CI/CD -> Secret Variables** section, setup the following 2 project variables:
* API_KEY = [your API KEY]
* USER_NAME = [your USER NAME@unity]
* You're almost done! To publish a version of your package, make sure all your changes are checked into Gitlab, then create a new tag to reflect the version you are publishing (ex. "v1.2.2"), **the tag will trigger a publish to Staging**. You can view progress you the publish request by switch over to the "CI / CD" part of your project.
1. Do it yourself CI
If you are using your own CI, it is still recommended that you use the `build.sh` wrapper script that comes with the starter kit, as it handle the installation of the actual CI build scripts for you.
Instead of calling `npm pack` and `npm publish` in the package root folder in your CI, use
```
./build.sh package-ci pack --git-head $CI_COMMIT_SHA --git-url $CI_REPOSITORY_URL
```
and
```
./build.sh package-ci publish --git-head $CI_COMMIT_SHA --git-url $CI_REPOSITORY_URL
```
respectively.
1. Test your package locally
Now that your package is published on the package manager's **staging** repository, you can test your package in the editor by creating a new project, and editing the project's `manifest.json` file to point to your staging package, as such:
```
dependencies: {
"com.[YourCompanyName].[sub-group].[your-package-name]": "0.1.0"
},
"registry": "https://staging-packages.unity.com"
```
## Get your package published to Production
Packages are promoted to the **production** repository from **staging**, described above.
Once you feel comfortable that your package is ready for prime time, and passes validation (Validation Suite), reach out to Unity so your package can be passed along to Release Management, for evaluation.
**Release management will validate your package content, and check that the editor/playmode tests are passed before promoting the package to production. You will receive a confirmation email once the package is in production.**
**You're almost done!**
At this point, your package is available on the cloud, but not discoverable through the editor:
1. Contact the Package Manager team to ask them to add your package to the list of discoverable package for the Unity Editor. All you need to provide is the package name (com.[YourCompanyName].[sub-group].[your-package-name])

7
Packages/com.unity.services.authentication/CHANGELOG.md.meta


fileFormatVersion: 2
guid: 06e5cc5b0f38f824b835fc371283773e
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

5
Packages/com.unity.services.authentication/Documentation~/com.unity.services.authentication.md


# About Authentication SDK
This is the Authentication SDK, a way to manage player accounts through the Unity User Authentication Service (UAS).
This package is currently in pre-release state and is not guaranteed to be fully functional.

8
Packages/com.unity.services.authentication/Editor.meta


fileFormatVersion: 2
guid: 9ab04733f4c8a4d7181b07dfa234aa46
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
Packages/com.unity.services.authentication/LICENSE.md.meta


fileFormatVersion: 2
guid: e71fc55799574654a9fa4ea97bcff964
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
Packages/com.unity.services.authentication/README.md.meta


fileFormatVersion: 2
guid: 3f7aaf8e8c5a3ed4f82b405fb280a2b5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
Packages/com.unity.services.authentication/Runtime.meta


fileFormatVersion: 2
guid: 0c7e209fd9875be4f927a2a934c4f5ce
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

40
Packages/com.unity.services.authentication/Third Party Notices.md


This package contains third-party software components governed by the license(s) indicated below:
----------
Component Name: moq4
License Type: BSD 3-Clause License
BSD 3-Clause License
Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions,
InSTEDD, and Contributors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Component Name: Newtonsoft.Json
License Type: MIT
The MIT License (MIT)
Copyright (c) 2007 James Newton-King
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

7
Packages/com.unity.services.authentication/Third Party Notices.md.meta


fileFormatVersion: 2
guid: 772ce27c160feed4cafd497fb9b43683
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
Packages/com.unity.services.authentication/package.json.meta


fileFormatVersion: 2
guid: ccb43312ae6774140ae13181bc71f2b8
PackageManifestImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

67
Packages/com.unity.services.authentication/CHANGELOG.md


# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.7.1-preview] - 2021-07-22
### Changed
- Updated the core SDK dependency to latest version.
## [0.7.0-preview] - 2021-07-22
### Changed
- Updated the core SDK dependency to latest version.
### Added
- Add missing xmldoc for the public functions.
## [0.6.0-preview] - 2021-07-15
### Added
- Add support for Unity Environments
## [0.5.0-preview] - 2021-06-16
### Changed
- Remove `SetOAuthClient()` as the authentication flow is simplified.
- Updated the initialization code to initialize with `UnityServices.Initialize()`
## [0.4.0-preview] - 2021-06-07
### Added
- Added Project Settings UI to configure ID providers.
- Added `SignInWithSteam`, `LinkWithSteam` functions.
- Changed the public interface of the Authentication service from a static instance and static methods to a singleton instance hidden behind an interface.
### Changed
- Change the public signature of `Authentication` to return a Task, as opposed to a IAsyncOperation
- Change the public API names of `Authentication` to `Async`
## [0.3.1-preview] - 2021-04-23
### Changed
- Change the `SignInFailed` event to take `AuthenticationException` instead of a string as parameter. It can provide more information for debugging purposes.
- Fixed the `com.unity.services.core` package dependency version.
## [0.3.0-preview] - 2021-04-21
### Added
- Added `SignInWithApple`, `LinkWithApple`, `SignInWithGoogle`, `LinkWithGoogle`, `SignInWithFacebook`, `LinkWithFacebook` functions.
- Added `SignInWithSessionToken`
- Added error codes used by the social scenarios to `AuthenticationError`.
## [0.2.3-preview] - 2021-03-23
### Changed
- Rename the package from `com.unity.services.identity` to `com.unity.services.authentication`. Renamed the internal types/methods, too.
## [0.2.2-preview] - 2021-03-15
### Added
- Core package integration
## [0.2.1-preview] - 2021-03-05
- Fixed dependency on Utilities package
## [0.2.0-preview] - 2021-03-05
- Removed requirement for OAuth client ID to be specified (automatically uses project default OAuth client)
## [0.1.0-preview] - 2021-01-18
### This is the first release of *com.unity.services.identity*.

5
Packages/com.unity.services.authentication/Editor/AssemblyInfo.cs


using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.Services.Authentication.EditorTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // For Moq

3
Packages/com.unity.services.authentication/Editor/AssemblyInfo.cs.meta


fileFormatVersion: 2
guid: 80f9842e95c141e59bcc9d49c93cc2e1
timeCreated: 1620833560

3
Packages/com.unity.services.authentication/Editor/AuthenticationAdminClient.cs.meta


fileFormatVersion: 2
guid: ca4a5cace103447794de02de329b8eeb
timeCreated: 1620234241

11
Packages/com.unity.services.authentication/Editor/AuthenticationAdminNetworkClient.cs.meta


fileFormatVersion: 2
guid: 45791e692f25c4a61adf3f50dc1397ac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Packages/com.unity.services.authentication/Editor/AuthenticationIdentifier.cs.meta


fileFormatVersion: 2
guid: 6ac6e0d63f116404caeed7d030ba58cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

47
Packages/com.unity.services.authentication/Editor/AuthenticationService.cs


using System;
using Unity.Services.Core.Editor;
namespace Unity.Services.Authentication.Editor
{
class AuthenticationService : IEditorGameService
{
/// <summary>
/// Name of the service
/// Used for error handling and service fetching
/// </summary>
public string Name => "Authentication Service";
/// <summary>
/// Identifier for the service
/// Used when registering and fetching the service
/// </summary>
public IEditorGameServiceIdentifier Identifier { get; } = new AuthenticationIdentifier();
/// <summary>
/// Flag used to determine whether COPPA Compliance should be adhered to
/// for this service
/// </summary>
public bool RequiresCoppaCompliance => false;
/// <summary>
/// Flag used to determine whether this service has a dashboard
/// </summary>
public bool HasDashboard => false;
/// <summary>
/// Getter for the formatted dashboard url
/// If <see cref="HasDashboard"/> is false, this field only need return null or empty string
/// </summary>
/// <returns>The formatted URL</returns>
public string GetFormattedDashboardUrl()
{
return null;
}
/// <summary>
/// The enabler which allows the service to toggle on/off
/// Can be set to null, in which case there would be no toggle
/// </summary>
public IEditorGameServiceEnabler Enabler { get; } = null;
}
}

11
Packages/com.unity.services.authentication/Editor/AuthenticationService.cs.meta


fileFormatVersion: 2
guid: 8907e4a6f69d84349b9fdf60013bdd52
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

3
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsElement.cs.meta


fileFormatVersion: 2
guid: 1f130c428a4b4feb9d46ecee3206cc34
timeCreated: 1620752364

47
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsHelper.cs


using System;
namespace Unity.Services.Authentication.Editor
{
static class AuthenticationSettingsHelper
{
internal static Exception ExtractException(Exception exception)
{
var aggregatedException = exception as AggregateException;
if (aggregatedException == null)
{
return exception;
}
if (aggregatedException.InnerExceptions.Count > 1)
{
// There are multiple exceptions aggregated, don't try to extract exception.
return exception;
}
// It returns the first exception.
return aggregatedException.InnerException;
}
internal static string ExceptionToString(Exception exception)
{
var errorMessage = "[ERROR] ";
var currentError = exception;
var firstError = true;
while (currentError != null)
{
if (!firstError)
{
errorMessage += "\n---> ";
}
else
{
firstError = false;
}
errorMessage += currentError.Message;
currentError = currentError.InnerException;
}
return errorMessage;
}
}
}

3
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsHelper.cs.meta


fileFormatVersion: 2
guid: 7caccdcd0f744a8d911a745661de6c5c
timeCreated: 1621631992

58
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsProvider.cs


using System;
using System.Collections.Generic;
using Unity.Services.Core.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.Services.Authentication.Editor
{
class AuthenticationSettingsProvider : EditorGameServiceSettingsProvider
{
const string k_Title = "Authentication";
AuthenticationSettingsProvider(SettingsScope scopes, IEnumerable<string> keywords = null)
: base(GenerateProjectSettingsPath(k_Title), scopes, keywords) {}
/// <summary>
/// Accessor for the operate service
/// Used to toggle and get dashboard access
/// </summary>
protected override IEditorGameService EditorGameService => EditorGameServiceRegistry.Instance.GetEditorGameService<AuthenticationIdentifier>();
/// <summary>
/// Title shown in the header for the project settings
/// </summary>
protected override string Title => k_Title;
/// <summary>
/// Description show in the header for the project settings
/// </summary>
protected override string Description => "This package provides a system for working with the Unity User Authentication Service (UAS), including log-in, player ID and access token retrieval, and session persistence.";
/// <inheritdoc/>
protected override VisualElement GenerateServiceDetailUI()
{
var settingsElement = new AuthenticationSettingsElement(AuthenticationAdminClientManager.Instance, CloudProjectSettings.projectId);
settingsElement.RefreshIdProviders();
return settingsElement;
}
/// <inheritdoc/>
protected override VisualElement GenerateUnsupportedDetailUI()
{
return GenerateServiceDetailUI();
}
/// <summary>
/// Method which adds your settings provider to ProjectSettings
/// </summary>
/// <returns>A <see cref="AuthenticationSettingsProvider"/>.</returns>
[SettingsProvider]
public static SettingsProvider CreateSettingsProvider()
{
return new AuthenticationSettingsProvider(SettingsScope.Project);
}
}
}

11
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsProvider.cs.meta


fileFormatVersion: 2
guid: 78b5efd28d743406b8682bcb71c787a3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

20
Packages/com.unity.services.authentication/Editor/AuthenticationTopMenu.cs


#if ENABLE_EDITOR_GAME_SERVICES
using System;
using UnityEditor;
namespace Unity.Services.Authentication.Editor
{
static class AuthenticationTopMenu
{
const int k_ConfigureMenuPriority = 100;
const int k_ToolsMenuPriority = k_ConfigureMenuPriority + 11;
const string k_ServiceMenuRoot = "Services/Authentication/";
[MenuItem(k_ServiceMenuRoot + "Configure", priority = k_ConfigureMenuPriority)]
static void ShowProjectSettings()
{
SettingsService.OpenProjectSettings("Project/Services/Authentication");
}
}
}
#endif

11
Packages/com.unity.services.authentication/Editor/AuthenticationTopMenu.cs.meta


fileFormatVersion: 2
guid: f35b6d8fe19bd49b386370e507468195
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

3
Packages/com.unity.services.authentication/Editor/IAuthenticationAdminClient.cs.meta


fileFormatVersion: 2
guid: a6e05710dedc4ca8904dd440ac8d523f
timeCreated: 1620232781

3
Packages/com.unity.services.authentication/Editor/IdProviderElement.cs.meta


fileFormatVersion: 2
guid: 47435640c6bd4c5085515305c09812b2
timeCreated: 1620320241

8
Packages/com.unity.services.authentication/Editor/Models.meta


fileFormatVersion: 2
guid: 4a4020826b7ea4ccaacf75ad3f61c1f3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

49
Packages/com.unity.services.authentication/Editor/Models/CreateIdProviderRequest.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class CreateIdProviderRequest
{
[Preserve]
public CreateIdProviderRequest() {}
[Preserve]
public CreateIdProviderRequest(IdProviderResponse body)
{
ClientId = body.ClientId;
ClientSecret = body.ClientSecret;
Type = body.Type;
Disabled = body.Disabled;
}
[JsonProperty("clientId")]
public string ClientId;
[JsonProperty("clientSecret")]
public string ClientSecret;
[JsonProperty("type")]
public string Type;
[JsonProperty("disabled")]
public bool Disabled;
public override bool Equals(Object obj)
{
// Check for null and compare run-time types.
if ((obj == null) || !GetType().Equals(obj.GetType()))
{
return false;
}
CreateIdProviderRequest c = (CreateIdProviderRequest)obj;
return (ClientId == c.ClientId) &&
(ClientSecret == c.ClientSecret) &&
(Disabled == c.Disabled) &&
(Type == c.Type);
}
}
}

11
Packages/com.unity.services.authentication/Editor/Models/CreateIdProviderRequest.cs.meta


fileFormatVersion: 2
guid: be1b1eaa739554966a83f3094a060c10
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

20
Packages/com.unity.services.authentication/Editor/Models/DeleteIdProviderRequest.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class DeleteIdProviderRequest
{
[Preserve]
public DeleteIdProviderRequest() {}
[JsonProperty("IdDomain")]
public string IdDomain;
// string type
[JsonProperty("type")]
public string Type;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/DeleteIdProviderRequest.cs.meta


fileFormatVersion: 2
guid: 8123abbc4107b4f96b214a0be8153b82
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

19
Packages/com.unity.services.authentication/Editor/Models/GetIdDomainResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class GetIdDomainResponse
{
[Preserve]
public GetIdDomainResponse() {}
[JsonProperty("id")]
public string Id;
[JsonProperty("name")]
public string Name;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/GetIdDomainResponse.cs.meta


fileFormatVersion: 2
guid: 9014e1c2ef9b94c00bb9aacb76012679
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

56
Packages/com.unity.services.authentication/Editor/Models/IdProviderResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class IdProviderResponse
{
[Preserve]
public IdProviderResponse() {}
[JsonIgnore]
public bool New;
[JsonProperty("clientId")]
public string ClientId;
[JsonProperty("clientSecret")]
public string ClientSecret;
[JsonProperty("type")]
public string Type;
[JsonProperty("disabled")]
public bool Disabled;
public IdProviderResponse Clone()
{
return new IdProviderResponse
{
New = New,
Type = Type,
ClientId = ClientId,
ClientSecret = ClientSecret,
Disabled = Disabled
};
}
public override bool Equals(Object obj)
{
// Check for null and compare run-time types.
if ((obj == null) || !GetType().Equals(obj.GetType()))
{
return false;
}
IdProviderResponse c = (IdProviderResponse)obj;
return (New == c.New) &&
(ClientId == c.ClientId) &&
(ClientSecret == c.ClientSecret) &&
(Disabled == c.Disabled) &&
(Type == c.Type);
}
}
}

11
Packages/com.unity.services.authentication/Editor/Models/IdProviderResponse.cs.meta


fileFormatVersion: 2
guid: 7eacdd408d38b48c899541aa578c5269
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

19
Packages/com.unity.services.authentication/Editor/Models/ListIdProviderResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class ListIdProviderResponse
{
[Preserve]
public ListIdProviderResponse() {}
[JsonProperty("total")]
public int Total;
[JsonProperty("results")]
public IdProviderResponse[] Results;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/ListIdProviderResponse.cs.meta


fileFormatVersion: 2
guid: 2daa2da5cf49d49f39454c147fce718c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

29
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeErrorResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
/// <summary>
/// The model for error response from authentication server.
/// </summary>
/// <remarks>
/// There is another field "details" in the error response. It provides additional details
/// to the error. It's ignored in this deserialized class since it's not needed by the client SDK.
/// </remarks>
[Serializable]
class TokenExchangeErrorResponse
{
[Preserve]
public TokenExchangeErrorResponse() {}
[JsonProperty("name")]
public string Name;
[JsonProperty("message")]
public string Message;
[JsonProperty("status")]
public int Status;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeErrorResponse.cs.meta


fileFormatVersion: 2
guid: c6f0eee34b47a4cb8b94023a4898c02d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

16
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeRequest.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class TokenExchangeRequest
{
[Preserve]
public TokenExchangeRequest() {}
[JsonProperty("token")]
public string Token;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeRequest.cs.meta


fileFormatVersion: 2
guid: e4bf54815194b46d4a6a172313afe524
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

16
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class TokenExchangeResponse
{
[Preserve]
public TokenExchangeResponse() {}
[JsonProperty("token")]
public string Token;
}
}

11
Packages/com.unity.services.authentication/Editor/Models/TokenExchangeResponse.cs.meta


fileFormatVersion: 2
guid: faea4b70d595b40938db3363e4ca22fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

44
Packages/com.unity.services.authentication/Editor/Models/UpdateIdProviderRequest.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Editor.Models
{
[Serializable]
class UpdateIdProviderRequest
{
[Preserve]
public UpdateIdProviderRequest() {}
[Preserve]
public UpdateIdProviderRequest(IdProviderResponse body)
{
ClientId = body.ClientId;
ClientSecret = body.ClientSecret;
Type = body.Type;
}
[JsonProperty("clientId")]
public string ClientId;
[JsonProperty("clientSecret")]
public string ClientSecret;
[JsonProperty("type")]
public string Type;
public override bool Equals(Object obj)
{
// Check for null and compare run-time types.
if ((obj == null) || !GetType().Equals(obj.GetType()))
{
return false;
}
UpdateIdProviderRequest c = (UpdateIdProviderRequest)obj;
return (ClientId == c.ClientId) &&
(ClientSecret == c.ClientSecret) &&
(Type == c.Type);
}
}
}

11
Packages/com.unity.services.authentication/Editor/Models/UpdateIdProviderRequest.cs.meta


fileFormatVersion: 2
guid: bdcbfea2e2c424771b46cfa662b4a798
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

3
Packages/com.unity.services.authentication/Editor/USS.meta


fileFormatVersion: 2
guid: 82d2f74434ae476295725ecf6f372b2e
timeCreated: 1620232007

41
Packages/com.unity.services.authentication/Editor/USS/AuthenticationStyleSheet.uss


.auth-progress {
-unity-text-align: middle-center;
font-size: 18px;
margin-top: 20px;
margin-bottom: 20px;
}
.auth-error {
margin-top: 10px;
margin-bottom: 10px;
color: red;
display: none;
}
.auth-id-providers-text {
font-size: 18px;
-unity-font-style: bold;
}
.auth-id-provider-container {
flex-direction: column;
margin: 10px;
}
.auth-id-provider-details {
margin-top: 10px;
}
.auth-id-providers-title {
flex-direction: row;
}
.auth-button-container {
flex-grow: 1;
flex-direction: row;
justify-content: flex-end;
}
.auth-danger-button {
color: red;
}

3
Packages/com.unity.services.authentication/Editor/USS/AuthenticationStyleSheet.uss.meta


fileFormatVersion: 2
guid: 72a4ecb8b8884295aa937c771cf80c39
timeCreated: 1620232067

3
Packages/com.unity.services.authentication/Editor/UXML.meta


fileFormatVersion: 2
guid: de6fee8b1a0b4e6daa6017f3473d3ae4
timeCreated: 1620232017

15
Packages/com.unity.services.authentication/Editor/UXML/AuthenticationProjectSettings.uxml


<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xmlns="UnityEngine.UIElements" editor-extension-mode="False">
<ui:VisualElement class="auth-id-provider-container">
<ui:TextElement text="Please wait..." class="auth-progress"/>
<ui:TextElement text="" class="auth-error"/>
<ui:VisualElement class="auth-id-providers-title">
<ui:TextElement text="ID Providers" class="auth-id-providers-text"/>
<ui:VisualElement class="auth-button-container">
<ui:VisualElement name="id-provider-type" />
<ui:Button name="id-provider-add" text="Add" display-tooltip-when-elided="true" />
<ui:Button name="id-provider-refresh" text="Refresh" display-tooltip-when-elided="true" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement class="auth-id-provider-list" />
</ui:VisualElement>
</ui:UXML>

3
Packages/com.unity.services.authentication/Editor/UXML/AuthenticationProjectSettings.uxml.meta


fileFormatVersion: 2
guid: f0cb46d7f4ea4218b998906b544b49fa
timeCreated: 1620232088

12
Packages/com.unity.services.authentication/Editor/UXML/IdProviderElement.uxml


<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns="UnityEngine.UIElements" editor-extension-mode="False">
<ui:Foldout class="auth-id-provider-details" value="false">
<ui:Toggle label="Enabled" name="id-provider-enabled" value="true"/>
<ui:TextField picking-mode="Ignore" label="Client ID" name="id-provider-client-id" max-length="128"/>
<ui:TextField picking-mode="Ignore" label="Client Secret" password="true" max-length="128" name="id-provider-client-secret"/>
<ui:VisualElement class="auth-button-container">
<ui:Button name="id-provider-save" text="Save" display-tooltip-when-elided="true" />
<ui:Button name="id-provider-cancel" text="Cancel" display-tooltip-when-elided="true" />
<ui:Button name="id-provider-delete" text="Delete" display-tooltip-when-elided="true" class="auth-danger-button" />
</ui:VisualElement>
</ui:Foldout>
</ui:UXML>

3
Packages/com.unity.services.authentication/Editor/UXML/IdProviderElement.uxml.meta


fileFormatVersion: 2
guid: 061197ecd39a4e678b8a9f37cc2140bb
timeCreated: 1620322985

10
Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.api


// This file is generated. Do not modify by hand.
// XML documentation file not found. To check if public methods have XML comments,
// make sure the XML doc file is present and located next to the scraped dll
namespace Unity.Services.Authentication.Editor
{
public struct AuthenticationIdentifier : Unity.Services.Core.Editor.IEditorGameServiceIdentifier
{
public virtual string GetKey();
}
}

7
Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.api.meta


fileFormatVersion: 2
guid: afe1708907a3546638d2c4aa4d67b510
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

23
Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.asmdef


{
"name": "Unity.Services.Authentication.Editor",
"rootNamespace": "",
"references": [
"Unity.Services.Core.Editor",
"Unity.Services.Core",
"Unity.Services.Core.Internal",
"Unity.Settings.Editor",
"Unity.Services.Authentication",
"Unity.Services.Authentication.Models"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": false,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

7
Packages/com.unity.services.authentication/Editor/Unity.Services.Authentication.Editor.asmdef.meta


fileFormatVersion: 2
guid: 2eed68446396f438a95293b27030ee23
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

294
Packages/com.unity.services.authentication/Editor/AuthenticationAdminClient.cs


using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Unity.Services.Authentication.Editor.Models;
using Unity.Services.Authentication.Models;
using Unity.Services.Authentication.Utilities;
using Unity.Services.Core.Internal;
using UnityEditor;
using Logger = Unity.Services.Authentication.Utilities.Logger;
[assembly: InternalsVisibleTo("Unity.Services.Authentication.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.Services.Authentication.EditorTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // For Moq
namespace Unity.Services.Authentication.Editor
{
static class AuthenticationAdminClientManager
{
internal static IAuthenticationAdminClient Instance { get; set; } = AuthenticationAdminClient();
static IAuthenticationAdminClient AuthenticationAdminClient()
{
IDateTimeWrapper dateTime = new DateTimeWrapper();
INetworkingUtilities networkUtilities = new NetworkingUtilities(null);
string orgId = GetOrganizationId();
var networkClient = new AuthenticationAdminNetworkClient("https://services.unity.com",
orgId,
CloudProjectSettings.projectId,
networkUtilities);
return new AuthenticationAdminClient(networkClient);
}
// GetOrganizationId will gets the organization id associated with this Unity project.
static string GetOrganizationId()
{
// This is a temporary workaround to get the Genesis organization foreign key for non-DevX enhanced Unity versions.
// When the eventual changes are backported into previous versions of Unity, this will no longer be necessary.
Assembly assembly = Assembly.GetAssembly(typeof(EditorWindow));
var unityConnectInstance = assembly.CreateInstance("UnityEditor.Connect.UnityConnect", false, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null, null); Type t = unityConnectInstance.GetType();
var projectInfo = t.GetProperty("projectInfo").GetValue(unityConnectInstance, null);
Type projectInfoType = projectInfo.GetType();
return projectInfoType.GetProperty("organizationForeignKey").GetValue(projectInfo, null) as string;
}
}
class AuthenticationAdminClient : IAuthenticationAdminClient
{
string m_IdDomain;
IAuthenticationAdminNetworkClient m_AuthenticationAdminNetworkClient;
string m_orgForeignKey;
string m_servicesGatewayToken;
string m_genesisToken;
internal enum ServiceCalled
{
TokenExchange,
AuthenticationAdmin
}
public AuthenticationAdminClient(IAuthenticationAdminNetworkClient networkClient, string genesisToken = "")
{
m_AuthenticationAdminNetworkClient = networkClient;
m_genesisToken = genesisToken;
}
public IAsyncOperation<string> GetIDDomain()
{
var asyncOp = new AsyncOperation<string>();
Action<string> getIdDomainFunc = token =>
{
var getDefaultIdDomainRequest = m_AuthenticationAdminNetworkClient.GetDefaultIdDomain(token);
getDefaultIdDomainRequest.Completed += request => HandleGetIdDomainAPICall(asyncOp, request);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => getIdDomainFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<IdProviderResponse> CreateIdProvider(string iddomain, CreateIdProviderRequest body)
{
var asyncOp = new AsyncOperation<IdProviderResponse>();
Action<string> createIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.CreateIdProvider(body, iddomain, token);
request.Completed += req => HandleIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => createIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<ListIdProviderResponse> ListIdProviders(string iddomain)
{
var asyncOp = new AsyncOperation<ListIdProviderResponse>();
Action<string> listIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.ListIdProvider(iddomain, token);
request.Completed += req => HandleListIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => listIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<IdProviderResponse> UpdateIdProvider(string iddomain, string type, UpdateIdProviderRequest body)
{
var asyncOp = new AsyncOperation<IdProviderResponse>();
Action<string> enableIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.UpdateIdProvider(body, iddomain, type, token);
request.Completed += req => HandleIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => enableIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<IdProviderResponse> EnableIdProvider(string iddomain, string type)
{
var asyncOp = new AsyncOperation<IdProviderResponse>();
Action<string> enableIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.EnableIdProvider(iddomain, type, token);
request.Completed += req => HandleIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => enableIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<IdProviderResponse> DisableIdProvider(string iddomain, string type)
{
var asyncOp = new AsyncOperation<IdProviderResponse>();
Action<string> disableIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.DisableIdProvider(iddomain, type, token);
request.Completed += req => HandleIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => disableIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IAsyncOperation<IdProviderResponse> DeleteIdProvider(string iddomain, string type)
{
var asyncOp = new AsyncOperation<IdProviderResponse>();
Action<string> deleteIdProviderFunc = token =>
{
var request = m_AuthenticationAdminNetworkClient.DeleteIdProvider(iddomain, type, token);
request.Completed += req => HandleIdProviderResponseApiCall(asyncOp, req);
};
getGenesisToken();
var tokenAsyncOp = ExchangeToken(m_genesisToken);
tokenAsyncOp.Completed += tokenAsyncOpResult => deleteIdProviderFunc(tokenAsyncOpResult?.Result);
return asyncOp;
}
public IdProviderResponse CloneIdProvider(IdProviderResponse x)
{
return x.Clone();
}
internal IAsyncOperation<string> ExchangeToken(string token)
{
var asyncOp = new AsyncOperation<string>();
var request = m_AuthenticationAdminNetworkClient.TokenExchange(token);
request.Completed += req => HandleTokenExchange(asyncOp, req);
return asyncOp;
}
void HandleGetIdDomainAPICall(AsyncOperation<string> asyncOp, IWebRequest<GetIdDomainResponse> request)
{
if (HandleError(asyncOp, request, ServiceCalled.AuthenticationAdmin))
{
return;
}
m_IdDomain = request?.ResponseBody?.Id;
asyncOp.Succeed(request?.ResponseBody?.Id);
}
void HandleTokenExchange(AsyncOperation<string> asyncOp, IWebRequest<TokenExchangeResponse> request)
{
if (HandleError(asyncOp, request, ServiceCalled.TokenExchange))
{
return;
}
var token = request?.ResponseBody?.Token;
m_servicesGatewayToken = token;
asyncOp.Succeed(token);
}
void HandleIdProviderResponseApiCall(AsyncOperation<IdProviderResponse> asyncOp, IWebRequest<IdProviderResponse> request)
{
if (HandleError(asyncOp, request, ServiceCalled.AuthenticationAdmin))
{
return;
}
asyncOp.Succeed(request?.ResponseBody);
}
void HandleListIdProviderResponseApiCall(AsyncOperation<ListIdProviderResponse> asyncOp, IWebRequest<ListIdProviderResponse> request)
{
if (HandleError(asyncOp, request, ServiceCalled.AuthenticationAdmin))
{
return;
}
asyncOp.Succeed(request?.ResponseBody);
}
void HandleEmptyResponseApiCall(AsyncOperation<IdProviderResponse> asyncOp, IWebRequest<IdProviderResponse> request)
{
if (HandleError(asyncOp, request, ServiceCalled.AuthenticationAdmin))
{
return;
}
asyncOp.Succeed(request?.ResponseBody);
}
internal bool HandleError<Q, T>(AsyncOperation<Q> asyncOp, IWebRequest<T> request, ServiceCalled sc)
{
if (!request.RequestFailed)
{
return false;
}
if (request.NetworkError)
{
asyncOp.Fail(new AuthenticationException(AuthenticationError.NetworkError));
return true;
}
Logger.LogError("Error message: " + request.ErrorMessage);
try
{
switch (sc)
{
case ServiceCalled.TokenExchange:
var tokenExchangeErrorResponse = JsonConvert.DeserializeObject<TokenExchangeErrorResponse>(request.ErrorMessage);
asyncOp.Fail(new AuthenticationException(tokenExchangeErrorResponse.Name, tokenExchangeErrorResponse.Message));
break;
case ServiceCalled.AuthenticationAdmin:
var authenticationAdminErrorResponse = JsonConvert.DeserializeObject<AuthenticationErrorResponse>(request.ErrorMessage);
asyncOp.Fail(new AuthenticationException(authenticationAdminErrorResponse.Title, authenticationAdminErrorResponse.Detail));
break;
default:
asyncOp.Fail(new AuthenticationException(AuthenticationError.UnknownError, "Unknown error"));
break;
}
}
catch (JsonException ex)
{
Logger.LogException(ex);
asyncOp.Fail(new AuthenticationException(AuthenticationError.UnknownError, "Failed to deserialize server response: " + request.ErrorMessage));
}
catch (Exception ex)
{
Logger.LogException(ex);
asyncOp.Fail(new AuthenticationException(AuthenticationError.UnknownError, "Unknown error deserializing server response: " + request.ErrorMessage));
}
return true;
}
void getGenesisToken()
{
if (m_genesisToken == "")
{
m_genesisToken = CloudProjectSettings.accessToken;
}
}
}
}

146
Packages/com.unity.services.authentication/Editor/AuthenticationAdminNetworkClient.cs


using System;
using System.Collections.Generic;
using Unity.Services.Authentication.Editor.Models;
using Unity.Services.Authentication.Utilities;
using UnityEngine;
namespace Unity.Services.Authentication.Editor
{
interface IAuthenticationAdminNetworkClient
{
IWebRequest<TokenExchangeResponse> TokenExchange(string token);
IWebRequest<GetIdDomainResponse> GetDefaultIdDomain(string token);
IWebRequest<IdProviderResponse> CreateIdProvider(CreateIdProviderRequest body, string idDomain, string token);
IWebRequest<ListIdProviderResponse> ListIdProvider(string idDomain, string token);
IWebRequest<IdProviderResponse> UpdateIdProvider(UpdateIdProviderRequest body, string idDomain, string type, string token);
IWebRequest<IdProviderResponse> EnableIdProvider(string idDomain, string type, string token);
IWebRequest<IdProviderResponse> DisableIdProvider(string idDomain, string type, string token);
IWebRequest<IdProviderResponse> DeleteIdProvider(string idDomain, string type, string token);
}
class AuthenticationAdminNetworkClient : IAuthenticationAdminNetworkClient
{
const string k_ServicesGatewayStem = "/api/player-identity/v1/organizations/";
const string k_GetDefaultIdDomainStem = "/iddomains/default";
const string k_TokenExchangeStem = "/api/auth/v1/genesis-token-exchange/unity";
readonly string m_ServicesGatewayHost;
readonly string m_GetDefaultIdDomainUrl;
readonly string m_TokenExchangeUrl;
readonly string m_OrganizationId;
readonly string m_ProjectId;
readonly INetworkingUtilities m_NetworkClient;
readonly Dictionary<string, string> m_CommonPlayerIdentityHeaders;
internal AuthenticationAdminNetworkClient(string servicesGatewayHost,
string organizationId,
string projectId,
INetworkingUtilities networkClient)
{
m_ServicesGatewayHost = servicesGatewayHost;
m_OrganizationId = organizationId;
m_ProjectId = projectId;
m_GetDefaultIdDomainUrl = servicesGatewayHost + k_ServicesGatewayStem + organizationId + k_GetDefaultIdDomainStem;
m_TokenExchangeUrl = servicesGatewayHost + k_TokenExchangeStem;
m_NetworkClient = networkClient;
m_CommonPlayerIdentityHeaders = new Dictionary<string, string>
{
["ProjectId"] = projectId,
// The Error-Version header enables RFC7807HttpError error responses
["Error-Version"] = "v1"
};
}
public IWebRequest<GetIdDomainResponse> GetDefaultIdDomain(string token)
{
return m_NetworkClient.Get<GetIdDomainResponse>(m_GetDefaultIdDomainUrl, addTokenHeader(m_CommonPlayerIdentityHeaders, token));
}
public IWebRequest<TokenExchangeResponse> TokenExchange(string token)
{
var body = new TokenExchangeRequest();
body.Token = token;
return m_NetworkClient.PostJson<TokenExchangeResponse>(m_TokenExchangeUrl, body);
}
public IWebRequest<IdProviderResponse> CreateIdProvider(CreateIdProviderRequest body, string idDomain, string token)
{
return m_NetworkClient.PostJson<IdProviderResponse>(CreateIdProviderUrl(idDomain), body, addTokenHeader(m_CommonPlayerIdentityHeaders, token));
}
public IWebRequest<ListIdProviderResponse> ListIdProvider(string idDomain, string token)
{
return m_NetworkClient.Get<ListIdProviderResponse>(ListIdProviderUrl(idDomain), addTokenHeader(m_CommonPlayerIdentityHeaders, token));
}
public IWebRequest<IdProviderResponse> UpdateIdProvider(UpdateIdProviderRequest body, string idDomain, string type, string token)
{
return m_NetworkClient.Put<IdProviderResponse>(UpdateIdProviderUrl(idDomain, type), body, addTokenHeader(m_CommonPlayerIdentityHeaders, token));
}
public IWebRequest<IdProviderResponse> EnableIdProvider(string idDomain, string type, string token)
{
return m_NetworkClient.Post<IdProviderResponse>(EnableIdProviderUrl(idDomain, type), addJsonHeader(addTokenHeader(m_CommonPlayerIdentityHeaders, token)));
}
public IWebRequest<IdProviderResponse> DisableIdProvider(string idDomain, string type, string token)
{
return m_NetworkClient.Post<IdProviderResponse>(DisableIdProviderUrl(idDomain, type), addJsonHeader(addTokenHeader(m_CommonPlayerIdentityHeaders, token)));
}
public IWebRequest<IdProviderResponse> DeleteIdProvider(string idDomain, string type, string token)
{
return m_NetworkClient.Delete<IdProviderResponse>(DeleteIdProviderUrl(idDomain, type), addTokenHeader(m_CommonPlayerIdentityHeaders, token));
}
Dictionary<string, string> addTokenHeader(Dictionary<string, string> d, string token)
{
var headers = new Dictionary<string, string>(d);
headers.Add("Authorization", "Bearer " + token);
return headers;
}
Dictionary<string, string> addJsonHeader(Dictionary<string, string> d)
{
var headers = new Dictionary<string, string>(d);
headers.Add("Content-Type", "application/json");
return headers;
}
string CreateIdProviderUrl(string idDomain)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps";
}
string ListIdProviderUrl(string idDomain)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps";
}
string UpdateIdProviderUrl(string idDomain, string type)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps/" + type;
}
string DeleteIdProviderUrl(string idDomain, string type)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps/" + type;
}
string EnableIdProviderUrl(string idDomain, string type)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps/" + type + "/enable";
}
string DisableIdProviderUrl(string idDomain, string type)
{
return m_ServicesGatewayHost + k_ServicesGatewayStem + m_OrganizationId + "/iddomains/" + idDomain + "/idps/" + type + "/disable";
}
}
}

18
Packages/com.unity.services.authentication/Editor/AuthenticationIdentifier.cs


using System;
using Unity.Services.Core.Editor;
namespace Unity.Services.Authentication.Editor
{
/// <summary>
/// Implementation of the <see cref="IEditorGameServiceIdentifier"/> for the Authentication package
/// </summary>
/// <remarks>This identifier MUST be public struct.</remarks>
public struct AuthenticationIdentifier : IEditorGameServiceIdentifier
{
/// <summary>
/// Key for the Authentication package
/// </summary>
/// <returns>The identifier of the game service.</returns>
public string GetKey() => "Authentication";
}
}

292
Packages/com.unity.services.authentication/Editor/AuthenticationSettingsElement.cs


using System;
using System.Collections.Generic;
using Unity.Services.Authentication.Editor.Models;
using Unity.Services.Core.Internal;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.Services.Authentication.Editor
{
class AuthenticationSettingsElement : VisualElement
{
const string k_Uxml = "Packages/com.unity.services.authentication/Editor/UXML/AuthenticationProjectSettings.uxml";
const string k_Uss = "Packages/com.unity.services.authentication/Editor/USS/AuthenticationStyleSheet.uss";
IAuthenticationAdminClient m_AdminClient;
string m_ProjectId;
string m_IdDomainId;
// Whether skip the confirmation window for tests/automation.
bool m_SkipConfirmation;
TextElement m_WaitingTextElement;
TextElement m_ErrorTextElement;
VisualElement m_AddIdProviderContainer;
List<string> m_AddIdProviderTypeChoices;
PopupField<string> m_AddIdProviderType;
Button m_RefreshButton;
Button m_AddButton;
VisualElement m_IdProviderListContainer;
/// <summary>
/// The text to show when the settings is waitng for an async operation to finish.
/// </summary>
public TextElement WaitingTextElement => m_WaitingTextElement;
/// <summary>
/// The text to show when there is an error.
/// </summary>
public TextElement ErrorTextElement => m_ErrorTextElement;
/// <summary>
/// The add ID provider choices in the dropdown list.
/// </summary>
public IEnumerable<string> AddIdProviderTypeChoices => m_AddIdProviderTypeChoices;
/// <summary>
/// The add ID provider dropdown list.
/// </summary>
public PopupField<string> AddIdProviderType => m_AddIdProviderType;
/// <summary>
/// The button to refresh the ID provider list.
/// </summary>
public Button RefreshButton => m_RefreshButton;
/// <summary>
/// The button to add a new ID provider.
/// </summary>
public Button AddButton => m_AddButton;
/// <summary>
/// The container to add ID providers.
/// </summary>
public VisualElement IdProviderListContainer => m_IdProviderListContainer;
/// <summary>
/// Event triggered when the <cref="AuthenticationSettingsElement"/> starts or finishes waiting for an async operation.
/// The first parameter of the callback is the sender.
/// The second parameter is true if it starts waiting, and false if it finishes waiting.
/// </summary>
public event Action<AuthenticationSettingsElement, bool> Waiting;
public AuthenticationSettingsElement(IAuthenticationAdminClient adminClient, string projectId, bool skipConfirmation = false)
{
m_AdminClient = adminClient;
m_ProjectId = projectId;
m_SkipConfirmation = skipConfirmation;
var containerAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_Uxml);
if (containerAsset != null)
{
var containerUI = containerAsset.CloneTree().contentContainer;
var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(k_Uss);
if (styleSheet != null)
{
containerUI.styleSheets.Add(styleSheet);
}
else
{
throw new Exception("Asset not found: " + k_Uss);
}
m_WaitingTextElement = containerUI.Q<TextElement>(className: "auth-progress");
m_ErrorTextElement = containerUI.Q<TextElement>(className: "auth-error");
m_RefreshButton = containerUI.Q<Button>("id-provider-refresh");
m_RefreshButton.clicked += RefreshIdProviders;
m_AddButton = containerUI.Q<Button>("id-provider-add");
m_AddButton.SetEnabled(false);
m_AddButton.clicked += AddIdProvider;
m_IdProviderListContainer = containerUI.Q<VisualElement>(className: "auth-id-provider-list");
m_AddIdProviderContainer = containerUI.Q<VisualElement>("id-provider-type");
Add(containerUI);
}
else
{
throw new Exception("Asset not found: " + k_Uxml);
}
}
public void RefreshIdProviders()
{
ShowWaiting();
if (m_IdDomainId == null)
{
GetIdDomain();
}
else
{
ListIdProviders();
}
}
void GetIdDomain()
{
var asyncOp = m_AdminClient.GetIDDomain();
asyncOp.Completed += OnGetIdDomainCompleted;
}
void OnGetIdDomainCompleted(IAsyncOperation<string> asyncOp)
{
if (asyncOp.Exception != null)
{
OnError(asyncOp.Exception);
return;
}
m_IdDomainId = asyncOp.Result;
ListIdProviders();
}
void ListIdProviders()
{
var asyncOp = m_AdminClient.ListIdProviders(m_IdDomainId);
asyncOp.Completed += OnListIdProvidersCompleted;
}
void OnListIdProvidersCompleted(IAsyncOperation<ListIdProviderResponse> asyncOp)
{
if (asyncOp.Exception != null)
{
OnError(asyncOp.Exception);
return;
}
m_IdProviderListContainer.Clear();
if (asyncOp.Result?.Results != null)
{
foreach (var provider in asyncOp.Result.Results)
{
CreateIdProviderElement(provider);
}
}
UpdateAddIdproviderList();
HideWaiting();
}
void UpdateAddIdproviderList()
{
var unusedIdProviders = new List<string>(IdProviderType.All);
foreach (var child in m_IdProviderListContainer.Children())
{
if (!(child is IdProviderElement))
{
continue;
}
var idProviderElement = (IdProviderElement)child;
unusedIdProviders.Remove(idProviderElement.SavedValue.Type);
}
unusedIdProviders.Sort();
m_AddIdProviderContainer.Clear();
m_AddIdProviderTypeChoices = unusedIdProviders;
if (unusedIdProviders.Count == 0)
{
m_AddButton.SetEnabled(false);
}
else
{
if (unusedIdProviders.Count > 0)
{
m_AddIdProviderType = new PopupField<string>(null, unusedIdProviders, 0);
m_AddIdProviderContainer.Add(m_AddIdProviderType);
}
m_AddButton.SetEnabled(true);
}
}
void AddIdProvider()
{
var idProvider = new IdProviderResponse
{
New = true,
Type = m_AddIdProviderType.value
};
CreateIdProviderElement(idProvider);
}
void OnError(Exception error)
{
error = AuthenticationSettingsHelper.ExtractException(error);
m_ErrorTextElement.style.display = DisplayStyle.Flex;
m_ErrorTextElement.text = AuthenticationSettingsHelper.ExceptionToString(error);
Debug.LogError(error);
HideWaiting();
}
void CreateIdProviderElement(IdProviderResponse idProvider)
{
var options = IdProviderOptions.GetOptions(idProvider.Type);
if (options == null)
{
// the SDK doesn't support the ID provider type yet. Skip.
return;
}
var idProviderElement = new IdProviderElement(m_IdDomainId, m_AdminClient, idProvider, options, m_SkipConfirmation);
m_IdProviderListContainer.Add(idProviderElement);
idProviderElement.Waiting += OnIdProviderWaiting;
idProviderElement.Deleted += OnIdProviderDeleted;
idProviderElement.Error += OnIdProviderError;
m_IdProviderListContainer.Add(idProviderElement);
UpdateAddIdproviderList();
}
void OnIdProviderWaiting(IdProviderElement sender, bool waiting)
{
if (waiting)
{
ShowWaiting();
}
else
{
HideWaiting();
}
}
void OnIdProviderDeleted(IdProviderElement sender)
{
m_IdProviderListContainer.Remove(sender);
UpdateAddIdproviderList();
}
void OnIdProviderError(IdProviderElement sender, Exception error)
{
OnError(error);
}
void ShowWaiting()
{
// clear previous error when a new async action is triggered.
m_ErrorTextElement.style.display = DisplayStyle.None;
m_ErrorTextElement.text = string.Empty;
m_WaitingTextElement.style.display = DisplayStyle.Flex;
SetEnabled(false);
Waiting?.Invoke(this, true);
}
void HideWaiting()
{
m_WaitingTextElement.style.display = DisplayStyle.None;
SetEnabled(true);
Waiting?.Invoke(this, false);
}
}
}

78
Packages/com.unity.services.authentication/Editor/IAuthenticationAdminClient.cs


using Unity.Services.Authentication.Editor.Models;
using Unity.Services.Core.Internal;
namespace Unity.Services.Authentication.Editor
{
static class IdProviderType
{
public const string Apple = "apple.com";
public const string Facebook = "facebook.com";
public const string Steam = "steampowered.com";
public const string Google = "google.com";
public static readonly string[] All =
{
Apple,
Facebook,
Google,
Steam
};
}
interface IAuthenticationAdminClient
{
/// <summary>
/// Get the ID domain associated with the project.
/// </summary>
/// <param name="projectId">The Unity project ID.</param>
/// <returns>Async operation with the id domain ID as the result.</returns>
IAsyncOperation<string> GetIDDomain();
/// <summary>
/// Lists all ID providers created for the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <returns>The list of ID Providers configured in the ID domain.</returns>
IAsyncOperation<ListIdProviderResponse> ListIdProviders(string iddomain);
/// <summary>
/// Create a new ID provider for the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <param name="request">The ID provider to create.</param>
/// <returns>The ID Provider created.</returns>
IAsyncOperation<IdProviderResponse> CreateIdProvider(string iddomain, CreateIdProviderRequest request);
/// <summary>
/// Update an ID provider for the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <param name="request">The ID provider to create.</param>
/// <returns>The ID Provider updated.</returns>
IAsyncOperation<IdProviderResponse> UpdateIdProvider(string iddomain, string type, UpdateIdProviderRequest request);
/// <summary>
/// Enable an ID provider for the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <param name="type">The type of the ID provider.</param>
/// <returns>The ID Provider updated.</returns>
IAsyncOperation<IdProviderResponse> EnableIdProvider(string iddomain, string type);
/// <summary>
/// Disable an ID provider for the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <param name="type">The type of the ID provider.</param>
/// <returns>The ID Provider updated.</returns>
IAsyncOperation<IdProviderResponse> DisableIdProvider(string iddomain, string type);
/// <summary>
/// Delete a specific ID provider from the organization's specified ID domain
/// </summary>
/// <param name="iddomain">The ID domain ID</param>
/// <param name="type">The type of the ID provider.</param>
/// <returns>The async operation to check whether the task is done.</returns>
IAsyncOperation<IdProviderResponse> DeleteIdProvider(string iddomain, string type);
}
}

399
Packages/com.unity.services.authentication/Editor/IdProviderElement.cs


using System;
using System.Collections.Generic;
using Unity.Services.Authentication.Editor.Models;
using Unity.Services.Core.Internal;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.Services.Authentication.Editor
{
class IdProviderOptions
{
public const string IdProviderApple = "apple.com";
public const string IdProviderGoogle = "google.com";
public const string IdProviderFacebook = "facebook.com";
public const string IdProviderSteam = "steampowered.com";
public string IdProviderType { get; set; }
public string DisplayName { get; set; }
public string ClientIdDisplayName { get; set; } = "Client ID";
public string ClientSecretDisplayName { get; set; } = "Client Secret";
public bool NeedClientSecret {get; set; }
static readonly Dictionary<string, IdProviderOptions> s_IdProviderOptions = new Dictionary<string, IdProviderOptions>
{
[IdProviderApple] = new IdProviderOptions
{
IdProviderType = IdProviderApple,
DisplayName = "Sign-in with Apple",
ClientIdDisplayName = "App ID",
NeedClientSecret = false
},
[IdProviderGoogle] = new IdProviderOptions
{
IdProviderType = IdProviderGoogle,
DisplayName = "Google",
ClientIdDisplayName = "Client ID",
NeedClientSecret = false
},
[IdProviderFacebook] = new IdProviderOptions
{
IdProviderType = IdProviderFacebook,
DisplayName = "Facebook",
ClientIdDisplayName = "App ID",
ClientSecretDisplayName = "App Secret",
NeedClientSecret = true
},
[IdProviderSteam] = new IdProviderOptions
{
IdProviderType = IdProviderSteam,
DisplayName = "Steam",
ClientIdDisplayName = "App ID",
ClientSecretDisplayName = "Key",
NeedClientSecret = true
}
};
public static IdProviderOptions GetOptions(string idProviderType)
{
if (!s_IdProviderOptions.ContainsKey(idProviderType))
{
return null;
}
return s_IdProviderOptions[idProviderType];
}
}
class IdProviderElement : VisualElement
{
const string k_ElementUxml = "Packages/com.unity.services.authentication/Editor/UXML/IdProviderElement.uxml";
string m_IdDomainId;
IAuthenticationAdminClient m_AdminClient;
IdProviderOptions m_Options;
Foldout m_Container;
Toggle m_Enabled;
TextField m_ClientId;
TextField m_ClientSecret;
Button m_SaveButton;
Button m_CancelButton;
Button m_DeleteButton;
// Whether skip the confirmation window for tests/automation.
bool m_SkipConfirmation;
/// <summary>
/// The foldout container to show or hide the ID provider details.
/// </summary>
public Foldout Container => m_Container;
/// <summary>
/// The toggle to control whether the ID provider is enabled.
/// </summary>
public Toggle EnabledToggle => m_Enabled;
/// <summary>
/// The text field to fill the client ID.
/// </summary>
public TextField ClientIdField => m_ClientId;
/// <summary>
/// The text field to fill the client secret.
/// </summary>
public TextField ClientSecretField => m_ClientSecret;
/// <summary>
/// The button to save the changes.
/// </summary>
public Button SaveButton => m_SaveButton;
/// <summary>
/// The button to cancel changes.
/// </summary>
public Button CancelButton => m_CancelButton;
/// <summary>
/// The button to delete the current ID provider.
/// </summary>
public Button DeleteButton => m_DeleteButton;
/// <summary>
/// Event triggered when the <cref="IdProviderElement"/> starts or finishes waiting for an async operation.
/// The first parameter of the callback is the sender.
/// The second parameter is true if it starts waiting, and false if it finishes waiting.
/// </summary>
public event Action<IdProviderElement, bool> Waiting;
/// <summary>
/// Event triggered when the current <cref="IdProviderElement"/> needs to be deleted by the container.
/// The parameter of the callback is the sender.
/// </summary>
public event Action<IdProviderElement> Deleted;
/// <summary>
/// Event triggered when the current <cref="IdProviderElement"/> catches an error.
/// The first parameter of the callback is the sender.
/// The second parameter is the exception caught by the element.
/// </summary>
public event Action<IdProviderElement, Exception> Error;
/// <summary>
/// The value saved on the server side.
/// </summary>
public IdProviderResponse SavedValue { get; set; }
/// <summary>
/// The value of that is about to be saved to the server.
/// </summary>
public IdProviderResponse CurrentValue { get; set; }
public bool Changed =>
SavedValue?.Type != CurrentValue?.Type ||
SavedValue?.Disabled != CurrentValue?.Disabled ||
(SavedValue?.ClientId ?? "") != (CurrentValue?.ClientId ?? "") ||
(SavedValue?.ClientSecret ?? "") != (CurrentValue?.ClientSecret ?? "");
public bool IsValid =>
!string.IsNullOrEmpty(CurrentValue.ClientId) &&
(!m_Options.NeedClientSecret || !string.IsNullOrEmpty(CurrentValue.ClientSecret));
public IdProviderElement(string idDomain, IAuthenticationAdminClient adminClient, IdProviderResponse savedValue, IdProviderOptions options, bool skipConfirmation = false)
{
m_IdDomainId = idDomain;
m_AdminClient = adminClient;
m_Options = options;
m_SkipConfirmation = skipConfirmation;
SavedValue = savedValue;
CurrentValue = SavedValue.Clone();
var containerAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_ElementUxml);
if (containerAsset != null)
{
var containerUI = containerAsset.CloneTree().contentContainer;
m_Container = containerUI.Q<Foldout>(className: "auth-id-provider-details");
m_Container.text = savedValue.Type;
// If the ID Provider element is new, default to unfold.
m_Container.value = SavedValue.New;
m_Enabled = containerUI.Q<Toggle>("id-provider-enabled");
m_Enabled.RegisterCallback<ChangeEvent<bool>>(OnEnabledChanged);
m_ClientId = containerUI.Q<TextField>("id-provider-client-id");
m_ClientId.label = options.ClientIdDisplayName;
m_ClientId.RegisterCallback<ChangeEvent<string>>(OnClientIdChanged);
m_ClientSecret = containerUI.Q<TextField>("id-provider-client-secret");
if (options.NeedClientSecret)
{
m_ClientSecret.label = options.ClientSecretDisplayName;
m_ClientSecret.RegisterCallback<ChangeEvent<string>>(OnClientSecretChanged);
}
else
{
m_ClientSecret.style.display = DisplayStyle.None;
}
m_SaveButton = containerUI.Q<Button>("id-provider-save");
m_SaveButton.SetEnabled(false);
m_SaveButton.clicked += OnSaveButtonClicked;
m_CancelButton = containerUI.Q<Button>("id-provider-cancel");
m_CancelButton.SetEnabled(false);
m_CancelButton.clicked += OnCancelButtonClicked;
m_DeleteButton = containerUI.Q<Button>("id-provider-delete");
m_DeleteButton.clicked += OnDeleteButtonClicked;
m_DeleteButton.SetEnabled(!savedValue.New);
ResetCurrentValue();
Add(containerUI);
}
else
{
throw new Exception("Asset not found: " + k_ElementUxml);
}
}
void RefreshButtons()
{
bool hasChanges = Changed;
m_SaveButton.SetEnabled(hasChanges && IsValid);
m_CancelButton.SetEnabled(hasChanges || SavedValue.New);
if (SavedValue.New)
{
m_DeleteButton.SetEnabled(false);
m_DeleteButton.style.display = DisplayStyle.None;
}
else
{
m_DeleteButton.SetEnabled(true);
m_DeleteButton.style.display = DisplayStyle.Flex;
}
}
void OnEnabledChanged(ChangeEvent<bool> e)
{
CurrentValue.Disabled = !e.newValue;
RefreshButtons();
}
void OnClientIdChanged(ChangeEvent<string> e)
{
CurrentValue.ClientId = e.newValue;
RefreshButtons();
}
void OnClientSecretChanged(ChangeEvent<string> e)
{
CurrentValue.ClientSecret = e.newValue;
RefreshButtons();
}
void OnSaveButtonClicked()
{
int option = DisplayDialogComplex("Save your changes", "Do you want to save the ID provider changes?", "Save", "Cancel", "");
switch (option)
{
case 0:
Waiting?.Invoke(this, true);
if (SavedValue.New)
{
var asyncOp = m_AdminClient.CreateIdProvider(m_IdDomainId, new CreateIdProviderRequest(CurrentValue));
asyncOp.Completed += OnSaveCompleted;
}
else
{
var body = new UpdateIdProviderRequest(CurrentValue);
var asyncOp = m_AdminClient.UpdateIdProvider(m_IdDomainId, CurrentValue.Type, body);
asyncOp.Completed += OnSaveCompleted;
}
break;
case 1:
break;
default:
Debug.LogError("Unrecognized option.");
break;
}
}
void OnSaveCompleted(IAsyncOperation<IdProviderResponse> asyncOp)
{
if (asyncOp.Exception != null)
{
Error?.Invoke(this, AuthenticationSettingsHelper.ExtractException(asyncOp.Exception));
Waiting?.Invoke(this, false);
return;
}
SavedValue = asyncOp.Result;
// Check enable/disable status
if (SavedValue.Disabled != CurrentValue.Disabled)
{
SavedValue.ClientSecret = CurrentValue.ClientSecret;
asyncOp = CurrentValue.Disabled ? m_AdminClient.DisableIdProvider(m_IdDomainId, CurrentValue.Type) : m_AdminClient.EnableIdProvider(m_IdDomainId, CurrentValue.Type);
asyncOp.Completed += OnEnableDisableCompleted;
return;
}
// Enable/disable is not changed
ResetCurrentValue();
RefreshButtons();
Waiting?.Invoke(this, false);
}
void OnEnableDisableCompleted(IAsyncOperation<IdProviderResponse> asyncOp)
{
// Handle enable/disable exception
if (asyncOp.Exception != null)
{
Error?.Invoke(this, AuthenticationSettingsHelper.ExtractException(asyncOp.Exception));
Waiting?.Invoke(this, false);
return;
}
// Only reset current value when no exception
SavedValue = asyncOp.Result;
ResetCurrentValue();
RefreshButtons();
Waiting?.Invoke(this, false);
}
void OnCancelButtonClicked()
{
if (SavedValue.New)
{
// It's a new ID provider and it hasn't been saved to the server yet.
// Simply trigger delete event to notify parent to remove the element from the list.
Deleted?.Invoke(this);
return;
}
ResetCurrentValue();
}
void ResetCurrentValue()
{
CurrentValue = SavedValue.Clone();
m_Enabled.value = !CurrentValue.Disabled;
m_ClientId.value = CurrentValue.ClientId ?? "";
m_ClientSecret.value = CurrentValue.ClientSecret ?? "";
RefreshButtons();
}
void OnDeleteButtonClicked()
{
int option = DisplayDialogComplex("Delete Request", "Do you want to delete the ID Provider?", "Delete", "Cancel", "");
switch (option)
{
// Delete
case 0:
Waiting?.Invoke(this, true);
var asyncOp = m_AdminClient.DeleteIdProvider(m_IdDomainId, CurrentValue.Type);
asyncOp.Completed += OnDeleteCompleted;
break;
// Cancel
case 1:
break;
default:
Debug.LogError("Unrecognized option.");
break;
}
}
void OnDeleteCompleted(IAsyncOperation<IdProviderResponse> asyncOp)
{
if (asyncOp.Exception != null)
{
Error?.Invoke(this, AuthenticationSettingsHelper.ExtractException(asyncOp.Exception));
Waiting?.Invoke(this, false);
return;
}
// Simply trigger delete event to notify parent to remove the element from the list.
Deleted?.Invoke(this);
ResetCurrentValue();
Waiting?.Invoke(this, false);
}
int DisplayDialogComplex(string title, string message, string ok, string cancel, string alt)
{
if (Application.isBatchMode || m_SkipConfirmation)
return 0;
return EditorUtility.DisplayDialogComplex(title, message, ok, cancel, alt);
}
}
}

5
Packages/com.unity.services.authentication/LICENSE.md


com.unity.services.authentication copyright © 2021 Unity Technologies SF
This software is subject to, and made available under, the Unity Operate Terms of Service (see https://unity3d.com/legal/one-operate-services-terms-of-service), and is an "Operate Service" as defined therein.
Unless expressly provided otherwise, the software under this license is made available strictly on an "AS IS" BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the terms of service for details on these and other terms and conditions.

79
Packages/com.unity.services.authentication/README.md


# Unity Services Authentication SDK
This package provides a system for working with the Unity User Authentication Service (UAS), including log-in, player ID and access token retrieval, and session persistence.
## Integration
The Authentication SDK is currently available on the UPM Candidates Repository. You will need to add the UPM Candidates Registry (https://artifactory.prd.it.unity3d.com/artifactory/api/npm/upm-candidates) as a Scoped Registry to your project. Once you have done that, you can add the package `com.unity.services.authentication` with the latest version: `0.7.1-preview`.
Once you have installed the Authentication package, you must link your Unity project to a Unity Cloud Project using the Services window.
The Authentication SDK automatically initializes itself on game start (no prefabs are required, and it will initialize regardless of the current scene), so the only integration steps are to start using the Authentication API in your code. The API is exposed via the `Authentication.Instance` object in the `Unity.Services.Authentication` namespace.
Once the player has been signed in, the Authentication SDK will monitor the expiration time of their access token and attempt to refresh it automatically. No further action is required.
On starting a game you may notice a `UnityServicesContainer` game object is created in the DontDestroyOnLoad area, with an Authentication component. This is how the Authentication SDK hooks onto the Unity lifecycle events that it requires, so if you destroy this object or any of its components, the Authentication system will cease to function. Some values are also cached into `PlayerPrefs`, so clearing all `PlayerPrefs` keys will require the player to sign in again from scratch on their next session rather than being able to continue their current session.
## Public API
### Sign-In API
* `AuthenticationService.Instance.SignInAnonymouslyAsync()`
* This triggers the anonymous sign-in processes, which may take some seconds to finish
* This requires no parameters
* Anonymous sign-in stores the Session Token in Unity PlayerPrefs until an explicit SignOut call is made, so if you simply quit the game before, anonymous sign-in can use the Session Token to let the same anonymous user continue
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.SignInWithSessionTokenAsync()`
* This triggers the sign-in of the user with the session token stored on the device.
* If there is no cached session token, the async operation fails with `AuthenticationError.ClientNoActiveSession`.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.SignInWithAppleAsync(string idToken)`
* This triggers the sign-in of the user with an ID token from Apple.
* Game developer is responsible for installing the necessary SDK and get the token from Apple.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.SignInWithGoogleAsync(string idToken)`
* This triggers the sign-in of the user with an ID token from Google.
* Game developer is responsible for installing the necessary SDK and get the token from Google.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.SignInWithFacebookAsync(string accessToken)`
* This triggers the sign-in of the user with an access token from Facebook.
* Game developer is responsible for installing the necessary SDK and get the token from Facebook.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.SignedIn`
* This is an event to which you can subscribe to be notified when the sign-in process has completed successfully
* `AuthenticationService.Instance.SignInFailed`
* This is an event to which you can subscribe to be notified when the sign-in process has failed for some reason
* `AuthenticationService.Instance.SignedOut`
* This is an event to which you can subscribe to be notified when the user has been signed out for some reason (either because `AuthenticationService.Instance.SignOut()` was called explicitly, or because of a rejection in an automatic system e.g. a refresh attempt was rejected for having an invalid token)
* `AuthenticationService.Instance.SignOut()`
* This triggers the sign-out process, which includes flushing all cached data and revocation of the access token
* If you are not signed in, this method will do nothing
* `AuthenticationService.Instance.LinkWithAppleAsync(string idToken)`
* This function links the current user with an ID token from Apple. The user can later sign-in with the linked Apple account.
* Game developer is responsible for installing the necessary SDK and get the token from Apple.
* If you attempt to link with an account that is already linked with another user, the async operation to fail with `AuthenticationError.EntityExists`.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.LinkWithGoogleAsync(string idToken)`
* This function links the current user with an ID token from Google. The user can later sign-in with the linked Google account.
* Game developer is responsible for installing the necessary SDK and get the token from Google.
* If you attempt to link with an account that is already linked with another user, the async operation to fail with `AuthenticationError.EntityExists`.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.LinkWithFacebookAsync(string accessToken)`
* This function links the current user with an access token from Facebook. The user can later sign-in with the linked Facebook account.
* Game developer is responsible for installing the necessary SDK and get the token from Facebook.
* If you attempt to link with an account that is already linked with another user, the async operation to fail with `AuthenticationError.EntityExists`.
* If you attempt to sign in while already signed in, this method will deliver a warning and set the async operation to fail with `AuthenticationError.ClientInvalidUserState`.
* `AuthenticationService.Instance.IsSignedIn`
* Returns true if the player is signed in
* Note that the player is still considered signed in until they explicitly call SignOut (or some automatic process causes explicit sign-out), so this will return true even if the access token has expired
* `AuthenticationService.Instance.PlayerId`
* This property exposes the ID of the player when they are signed in, or null if they are not
* `AuthenticationService.Instance.AccessToken`
* Returns the raw string of the current access token, or null if no valid token is available (e.g. the player is signed in but the token has expired and could not be refreshed)
* This value is updated automatically by the refresh process, so consumers should NOT cache this value
### Additional Methods
* `AuthenticationService.Instance.SetLogLevel(LogLevel level)`
* This enables verbose logging by the Authentication SDK, including exposing the underlying state machine transitions, web request successes and other details that might assist debugging
* By default this is set to Errors Only

3
Packages/com.unity.services.authentication/Runtime/AuthenticationAsyncOperation.cs.meta


fileFormatVersion: 2
guid: e7b99cac88a14e459ace5e1c4f22a015
timeCreated: 1618596342

58
Packages/com.unity.services.authentication/Runtime/AuthenticationError.cs


using System;
namespace Unity.Services.Authentication
{
/// <summary>
/// AuthenticationError lists the error codes to expect from <c>AuthenticationException</c> and failed events.
/// </summary>
public static class AuthenticationError
{
/// <summary>
/// This is a client error that is returned when the user is not in the right state.
/// For example, calling SignOut when the user is already signed out will result in this error.
/// </summary>
public const string ClientInvalidUserState = "CLIENT_INVALID_USER_STATE";
/// <summary>
/// This is a client error that is returned when trying to sign-in with session token while there is no cached
/// session token.
/// </summary>
public const string ClientNoActiveSession = "CLIENT_NO_ACTIVE_SESSION";
/// <summary>
/// The error returned when auth code parameter is not found in the authorize response.
/// </summary>
public const string AuthCodeNotFound = "AUTH_CODE_NOT_FOUND";
/// <summary>
/// The error returned when the access token returned by server is invalid.
/// </summary>
public const string InvalidAccessToken = "INVALID_ACCESS_TOKEN";
/// <summary>
/// The error returned when the entity with the same key already exists.
/// It happens when a user tries to link a social account while the social account is already linked with another user.
/// </summary>
public const string EntityExists = "ENTITY_EXISTS";
/// <summary>
/// The error returned when the parameter is missing or not in the right format.
/// </summary>
public const string InvalidParameters = "INVALID_PARAMETERS";
/// <summary>
/// The error returned when the permission is denied using the token provided.
/// </summary>
public const string PermissionDenied = "PERMISSION_DENIED";
/// <summary>
/// This is a network error when calling APIs.
/// </summary>
public const string NetworkError = "NETWORK_ERROR";
/// <summary>
/// This is an unknown error. It happens when there is an unexpected server response.
/// </summary>
public const string UnknownError = "UNKNOWN_ERROR";
}
}

3
Packages/com.unity.services.authentication/Runtime/AuthenticationError.cs.meta


fileFormatVersion: 2
guid: 67eb6c6266af413384b674771544e0bf
timeCreated: 1616186210

49
Packages/com.unity.services.authentication/Runtime/AuthenticationException.cs


using System;
namespace Unity.Services.Authentication
{
/// <summary>
/// AuthenticationException represents a runtime exception from authentication.
/// </summary>
public class AuthenticationException : Exception
{
/// <summary>
/// The error code is the identifier for the type of error to handle.
/// Checkout <c>AuthenticationError</c> for error codes.
/// </summary>
public string ErrorCode { get; private set; }
/// <summary>
/// Constructor of the AuthenticationException with error code.
/// </summary>
/// <param name="errorCode">The error code for AuthenticationException.</param>
public AuthenticationException(string errorCode)
: base(errorCode)
{
ErrorCode = errorCode;
}
/// <summary>
/// Constructor of the AuthenticationException with error code and a message.
/// </summary>
/// <param name="errorCode">The error code for AuthenticationException.</param>
/// <param name="message">The additional message that helps to debug.</param>
public AuthenticationException(string errorCode, string message)
: base(errorCode + ": " + message)
{
ErrorCode = errorCode;
}
/// <summary>
/// Constructor of the AuthenticationException with error code, a message and inner exception.
/// </summary>
/// <param name="errorCode">The error code for AuthenticationException.</param>
/// <param name="message">The additional message that helps to debug.</param>
/// <param name="innerException">The cause of the exception.</param>
public AuthenticationException(string errorCode, string message, Exception innerException)
: base(errorCode + ": " + message, innerException)
{
ErrorCode = errorCode;
}
}
}

3
Packages/com.unity.services.authentication/Runtime/AuthenticationException.cs.meta


fileFormatVersion: 2
guid: 6be08ac0648d4bc09c9100856ab323c1
timeCreated: 1616186221

11
Packages/com.unity.services.authentication/Runtime/AuthenticationNetworkClient.cs.meta


fileFormatVersion: 2
guid: cb4a26d0e0091194581e3117bbf91a6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Packages/com.unity.services.authentication/Runtime/AuthenticationService.cs.meta


fileFormatVersion: 2
guid: 59bf095b5a6ab49ebb2364fbda09f975
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Packages/com.unity.services.authentication/Runtime/AuthenticationServiceInternal.cs.meta


fileFormatVersion: 2
guid: 5a4bdb16b51b6412dbd984e55e006a74
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

48
Packages/com.unity.services.authentication/Runtime/CodeChallengeGenerator.cs


using System;
using System.Security.Cryptography;
using System.Text;
namespace Unity.Services.Authentication
{
interface ICodeChallengeGenerator
{
string GenerateCode();
string GenerateStateString();
}
class CodeChallengeGenerator : ICodeChallengeGenerator
{
internal const int k_CodeLength = 128;
const string k_CodeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
readonly StringBuilder m_CodeBuilder;
internal CodeChallengeGenerator()
{
m_CodeBuilder = new StringBuilder(k_CodeLength);
}
public string GenerateCode()
{
var randomBytes = new byte[k_CodeLength];
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
randomNumberGenerator.GetBytes(randomBytes);
}
m_CodeBuilder.Clear();
for (var i = 0; i < k_CodeLength; i++)
{
m_CodeBuilder.Append(k_CodeChars[randomBytes[i] % k_CodeChars.Length]);
}
return m_CodeBuilder.ToString();
}
public string GenerateStateString()
{
return Guid.NewGuid().ToString();
}
}
}

11
Packages/com.unity.services.authentication/Runtime/CodeChallengeGenerator.cs.meta


fileFormatVersion: 2
guid: 069948c258b7aa546b3f2841139f3e73
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
Packages/com.unity.services.authentication/Runtime/Core.meta


fileFormatVersion: 2
guid: 020c5be1b3461430e835bf14328b694b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
Packages/com.unity.services.authentication/Runtime/IAuthenticationService.cs.meta


fileFormatVersion: 2
guid: 8b263d7eb2ea840a3be159f04d5e224f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
Packages/com.unity.services.authentication/Runtime/JwtDecoder.cs.meta


fileFormatVersion: 2
guid: a386fd072e97bd74986da1d3347910ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

3
Packages/com.unity.services.authentication/Runtime/Models.meta


fileFormatVersion: 2
guid: 9e31aad287e446f8a33a3b11a90e7af3
timeCreated: 1616197222

44
Packages/com.unity.services.authentication/Runtime/Models/AccessToken.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Models
{
class AccessToken : BaseJwt
{
[Preserve]
public AccessToken() {}
[JsonProperty("aud")]
public string[] Audience;
[JsonProperty("client_id")]
public string ClientId;
[JsonProperty("ext")]
public AccessTokenExtraClaims Extra;
[JsonProperty("iss")]
public string Issuer;
[JsonProperty("jti")]
public string JwtId;
[JsonProperty("project_id")]
public string ProjectId;
[JsonProperty("scp")]
public string[] Scope;
[JsonProperty("sub")]
public string Subject;
}
class AccessTokenExtraClaims
{
[Preserve]
public AccessTokenExtraClaims() {}
// Unused at this time but left in for completeness
}
}

11
Packages/com.unity.services.authentication/Runtime/Models/AccessToken.cs.meta


fileFormatVersion: 2
guid: 2b3d05823c6da42269150d95fe724619
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

29
Packages/com.unity.services.authentication/Runtime/Models/AuthenticationErrorResponse.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Models
{
/// <summary>
/// The model for error response from authentication server.
/// </summary>
/// <remarks>
/// There is another field "details" in the error response. It provides additional details
/// to the error. It's ignored in this deserialized class since it's not needed by the client SDK.
/// </remarks>
[Serializable]
class AuthenticationErrorResponse
{
[Preserve]
public AuthenticationErrorResponse() {}
[JsonProperty("title")]
public string Title;
[JsonProperty("detail")]
public string Detail;
[JsonProperty("status")]
public int Status;
}
}

11
Packages/com.unity.services.authentication/Runtime/Models/AuthenticationErrorResponse.cs.meta


fileFormatVersion: 2
guid: fce1a01a480e04f4492c095e03f77901
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

39
Packages/com.unity.services.authentication/Runtime/Models/BaseJwt.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Models
{
class BaseJwt
{
[Preserve]
public BaseJwt() {}
[JsonProperty("exp")]
public int ExpirationTimeUnix;
[JsonProperty("iat")]
public int IssuedAtTimeUnix;
[JsonProperty("nbf")]
public int NotBeforeTimeUnix;
[JsonIgnore]
public DateTime ExpirationTime => ConvertTimestamp(ExpirationTimeUnix);
[JsonIgnore]
public DateTime IssuedAtTime => ConvertTimestamp(IssuedAtTimeUnix);
[JsonIgnore]
public DateTime NotBeforeTime => ConvertTimestamp(NotBeforeTimeUnix);
protected DateTime ConvertTimestamp(int timestamp)
{
if (timestamp != 0)
{
var dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
return dateTimeOffset.DateTime;
}
throw new Exception("Token does not contain a value for this timestamp.");
}
}
}

11
Packages/com.unity.services.authentication/Runtime/Models/BaseJwt.cs.meta


fileFormatVersion: 2
guid: ead3856418b0b4b66a300d58259bf97f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

19
Packages/com.unity.services.authentication/Runtime/Models/ExternalTokenRequest.cs


using System;
using Newtonsoft.Json;
using UnityEngine.Scripting;
namespace Unity.Services.Authentication.Models
{
[Serializable]
class ExternalTokenRequest
{
[Preserve]
public ExternalTokenRequest() {}
[JsonProperty("idProvider")]
public string IdProvider;
[JsonProperty("token")]
public string Token;
}
}

11
Packages/com.unity.services.authentication/Runtime/Models/ExternalTokenRequest.cs.meta


fileFormatVersion: 2
guid: db94570f7a8334ebf8a8a9a53f5508b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存