├── CHANGELOG.md ├── console-csharp-trustFrameworkPolicy ├── App.config ├── packages.config ├── Constants.cs ├── Properties │ └── AssemblyInfo.cs ├── UserMode.cs ├── AuthenticationHelper.cs ├── B2CPolicyClient.csproj └── Program.cs ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── console-csharp-trustFrameworkPolicy.sln ├── LICENSE.md ├── DeployToB2c.ps1 ├── CONTRIBUTING.md ├── README.md ├── CICDINSTRUCTIONS.md └── .gitignore /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26403.3 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "B2CPolicyClient", "console-csharp-trustFrameworkPolicy\B2CPolicyClient.csproj", "{6A3A724C-5985-494F-9FFE-2C1DD10E789F}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace console_csharp_trustframeworkpolicy 2 | { 3 | internal class Constants 4 | { 5 | // TODO: update "ClientIdForUserAuthn" with your app guid and "Tenant" with your tenant name 6 | // see README.md for instructions 7 | // Client ID is the application guid used uniquely identify itself to the v2.0 authentication endpoint 8 | public const string ClientIdForUserAuthn = "ENTER_YOUR_CLIENT_ID"; 9 | // Your tenant Name, for example "myb2ctenant.onmicrosoft.com" 10 | public const string Tenant = "ENTER_YOUR_TENANT_NAME"; 11 | 12 | // leave these as-is - URIs used for auth 13 | public const string AuthorityUri = "https://login.microsoftonline.com/" + Tenant + "/oauth2/v2.0/token"; 14 | public const string RedirectUriForAppAuthn = "https://login.microsoftonline.com"; 15 | 16 | // leave these as-is - Private Preview Graph URIs for custom trust framework policy 17 | public const string TrustFrameworkPolicesUri = "https://graph.microsoft.com/beta/trustFramework/policies"; 18 | public const string TrustFrameworkPolicyByIDUri = "https://graph.microsoft.com/beta/trustFramework/policies/{0}/$value"; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("B2CPolicyClient")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("B2CPolicyClient")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6a3a724c-5985-494f-9ffe-2c1dd10e789f")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /DeployToB2c.ps1: -------------------------------------------------------------------------------- 1 | [Cmdletbinding()] 2 | Param( 3 | [Parameter(Mandatory=$true)][string]$ClientID, 4 | [Parameter(Mandatory=$true)][string]$ClientSecret, 5 | [Parameter(Mandatory=$true)][string]$TenantId, 6 | [Parameter(Mandatory=$true)][string]$PolicyId, 7 | [Parameter(Mandatory=$true)][string]$PathToFile 8 | ) 9 | 10 | try{ 11 | $body = @{grant_type="client_credentials";scope="https://graph.microsoft.com/.default";client_id=$ClientID;client_secret=$ClientSecret} 12 | 13 | $response=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token -Method Post -Body $body 14 | $token=$response.access_token 15 | 16 | $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 17 | $headers.Add("Content-Type", 'application/xml') 18 | $headers.Add("Authorization", 'Bearer ' + $token) 19 | 20 | $graphuri = 'https://graph.microsoft.com/beta/trustframework/policies/'+$PolicyId+'/$value' 21 | $policycontent = Get-Content $PathToFile 22 | $response=Invoke-RestMethod -Uri $graphuri -Method Put -Body $policycontent -Headers $headers 23 | 24 | Write-Host "Policy" $PolicyId "uploaded successfully." 25 | } 26 | catch 27 | { 28 | Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 29 | 30 | $_ 31 | 32 | $streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream()) 33 | $ErrResp = $streamReader.ReadToEnd() 34 | $streamReader.Close() 35 | 36 | $ErrResp 37 | 38 | exit 1 39 | } 40 | 41 | exit 0 42 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/UserMode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Threading.Tasks; 4 | using Microsoft.Graph; 5 | using System.Net.Http; 6 | 7 | namespace console_csharp_trustframeworkpolicy 8 | { 9 | internal class UserMode 10 | { 11 | public static GraphServiceClient client; 12 | 13 | internal static string ContentType = "application/xml"; 14 | public static bool CreateGraphClient() 15 | { 16 | try 17 | { 18 | //********************************************************************* 19 | // setup Microsoft Graph Client for delegated user. 20 | //********************************************************************* 21 | client = AuthenticationHelper.GetAuthenticatedClientForUser(); 22 | return true; 23 | } 24 | catch (Exception ex) 25 | { 26 | Console.ForegroundColor = ConsoleColor.Red; 27 | Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); 28 | if (ex.InnerException != null) 29 | { 30 | //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx 31 | //InnerException Message will contain the HTTP error status codes mentioned in the link above 32 | Console.WriteLine("Error detail: {0}", ex.InnerException.Message); 33 | } 34 | Console.ResetColor(); 35 | Console.ReadKey(); 36 | return false; 37 | } 38 | } 39 | 40 | public static HttpRequestMessage HttpGet(string uri) 41 | { 42 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri); 43 | AuthenticationHelper.AddHeaders(request); 44 | return request; 45 | } 46 | 47 | public static HttpRequestMessage HttpGetID(string uri, string id) 48 | { 49 | string uriWithID = String.Format(uri, id); 50 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uriWithID); 51 | AuthenticationHelper.AddHeaders(request); 52 | return request; 53 | } 54 | 55 | public static HttpRequestMessage HttpPutID(string uri, string id, string xml) 56 | { 57 | string uriWithID = String.Format(uri, id); 58 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, uriWithID); 59 | AuthenticationHelper.AddHeaders(request); 60 | request.Content = new StringContent(xml, Encoding.UTF8, ContentType); 61 | return request; 62 | } 63 | 64 | public static HttpRequestMessage HttpPost(string uri, string xml) 65 | { 66 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri); 67 | AuthenticationHelper.AddHeaders(request); 68 | request.Content = new StringContent(xml, Encoding.UTF8, ContentType); 69 | return request; 70 | } 71 | 72 | public static HttpRequestMessage HttpDeleteID(string uri, string id) 73 | { 74 | string uriWithID = String.Format(uri, id); 75 | HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, uriWithID); 76 | AuthenticationHelper.AddHeaders(request); 77 | return request; 78 | } 79 | 80 | public static void LoginAsAdmin() 81 | { 82 | Console.WriteLine("Login as a global admin of the tenant (example: admin@myb2c.onmicrosoft.com"); 83 | Console.WriteLine("============================="); 84 | 85 | if (CreateGraphClient()) 86 | { 87 | User user = client.Me.Request().GetAsync().Result; 88 | Console.WriteLine("Current user: Id: {0} UPN: {1}", user.Id, user.UserPrincipalName); 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 6 | 7 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Manage custom polices in Azure AD B2C using Graph API 2 | [!NOTE] This feature is now in public preview 3 | 4 | This is a sample command line tool that demonstrates managing custom trust framework policies (custom policy for short) and Policy keys in an Azure AD B2C tenant. [Custom policy](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-overview-custom) allows you to customize every aspect of the authentication flow. Azure AD B2C uses [Policy keys](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-get-started-custom#create-the-encryption-key) to manage your secrets. 5 | 6 | ## Features 7 | 8 | This sample demonstrates the following: 9 | 10 | * **Create** a custom policy 11 | * **Read** details of a custom policy 12 | * **Update** a custom policy 13 | * **Delete** a custom policy 14 | * **List** all custom policies 15 | 16 | ## Getting Started 17 | 18 | ### Prerequisites 19 | 20 | This sample requires the following: 21 | 22 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads) 23 | * [Azure AD B2C tenant](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-get-started) 24 | 25 | 26 | ### Quickstart 27 | 28 | #### Create global administrator 29 | 30 | * An global administrator account is required to run admin-level operations and to consent to application permissions. (for example: admin@myb2ctenant.onmicrosoft.com) 31 | 32 | #### Register the delegated permissions application 33 | 34 | 1. Sign in to the [Application Registration Portal](https://apps.dev.microsoft.com/) using your Microsoft account. 35 | 1. Select **Add an app**, and enter a friendly name for the application (such as **Console App for Microsoft Graph (Delegated perms)**). Click **Create**. 36 | 1. On the application registration page, select **Add Platform**. Select the **Native App** tile and save your change. The **delegated permissions** operations in this sample use permissions that are specified in the AuthenticationHelper.cs file. This is why you don't need to assign any permissions to the app on this page. 37 | 1. Open the solution and then the Constants.cs file in Visual Studio. 38 | 1. Make the **Application Id** value for this app the value of the **ClientIdForUserAuthn** string. 39 | 1. Update **Tenant** with the name of your tenant. (for example: myb2ctenantname.onmicrosoft.com) 40 | 41 | #### Build and run the sample 42 | 43 | 1. Open the sample solution in Visual Studio. 44 | 1. Replace the tenant name and application id in Constants.cs by following [Register the delegated permissions application](#register-the-delegated-permissions-application) 45 | 1. Build the sample. 46 | 1. Using cmd or PowerShell, navigate to /bin/Debug. Run the executable **B2CPolicyClient.exe**. 47 | 1. Sign in as a global administrator. (for example: admin@myb2ctenant.onmicrosoft.com) 48 | 1. The output will show the results of calling the Graph API for trustFrameworkPolices. 49 | 50 | ## Questions and comments 51 | 52 | Questions about this sample should be posted to [Stack Overflow](https://stackoverflow.com/questions/tagged/azure-ad-b2c). Make sure that your questions or comments are tagged with [azure-ad-b2c]. 53 | 54 | ## Contributing 55 | 56 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). 57 | 58 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 59 | 60 | ## Resources 61 | 62 | The sample uses the Microsoft Authentication Library (MSAL) for authentication. The sample demonstrates both delegated admin permissions. (app only permissions are not supported yet) 63 | 64 | **Delegated permissions** are used by apps that have a signed-in user present (in this case tenant administrator). For these apps either the user or an administrator consents to the permissions that the app requests and the app is delegated permission to act as the signed-in user when making calls to Microsoft Graph. Some delegated permissions can be consented to by non-administrative users, but some higher-privileged permissions require administrator consent. 65 | 66 | See [Delegated permissions, Application permissions, and effective permissions](https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#delegated-permissions-application-permissions-and-effective-permissions) for more information about these permission types. 67 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/AuthenticationHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Net.Http.Headers; 4 | using System.Net.Http; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using Microsoft.Graph; 8 | using Microsoft.Identity.Client; 9 | 10 | namespace console_csharp_trustframeworkpolicy 11 | { 12 | class AuthenticationHelper 13 | { 14 | // public preview, this API will require Policy.ReadWrite.TrustFramework as an admin-only scope, 15 | // so authorization will fail if you sign in with a non-admin account. // For now, this API is only accessible on tenants that have been whitelisted 16 | public static string[] Scopes = { "User.Read", "Policy.ReadWrite.TrustFramework" }; 17 | 18 | public static PublicClientApplication IdentityClientApp = new PublicClientApplication(Constants.ClientIdForUserAuthn); 19 | public static string TokenForUser = null; 20 | public static DateTimeOffset Expiration; 21 | 22 | private static GraphServiceClient graphClient = null; 23 | 24 | // Get an access token for the given context and resourceId. An attempt is first made to 25 | // acquire the token silently. If that fails, then we try to acquire the token by prompting the user. 26 | public static GraphServiceClient GetAuthenticatedClientForUser() 27 | { 28 | // Create Microsoft Graph client. 29 | try 30 | { 31 | graphClient = new GraphServiceClient( 32 | "https://graph.microsoft.com/v1.0", 33 | new DelegateAuthenticationProvider( 34 | async (requestMessage) => 35 | { 36 | var token = await GetTokenForUserAsync(); 37 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token); 38 | // This header has been added to identify usage of this sample in the Microsoft Graph service. You are free to remove it without impacting functionlity. 39 | requestMessage.Headers.Add("SampleID", "console-csharp-trustframeworkpolicy"); 40 | })); 41 | return graphClient; 42 | } 43 | 44 | catch (Exception ex) 45 | { 46 | Debug.WriteLine("Could not create a graph client: " + ex.Message); 47 | } 48 | 49 | return graphClient; 50 | } 51 | 52 | public static void AddHeaders(HttpRequestMessage requestMessage) 53 | { 54 | if(TokenForUser == null) 55 | { 56 | Debug.WriteLine("Call GetAuthenticatedClientForUser first"); 57 | } 58 | 59 | try 60 | { 61 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", TokenForUser); 62 | requestMessage.Headers.Add("SampleID", "console-csharp-trustframeworkpolicy"); 63 | } 64 | catch (Exception ex) 65 | { 66 | Debug.WriteLine("Could not add headers to HttpRequestMessage: " + ex.Message); 67 | } 68 | } 69 | 70 | /// 71 | /// Get Token for User. 72 | /// 73 | /// Token for user. 74 | public static async Task GetTokenForUserAsync() 75 | { 76 | AuthenticationResult authResult; 77 | try 78 | { 79 | authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, IdentityClientApp.Users.First()); 80 | TokenForUser = authResult.AccessToken; 81 | } 82 | 83 | catch (Exception) 84 | { 85 | if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5)) 86 | { 87 | authResult = await IdentityClientApp.AcquireTokenAsync(Scopes); 88 | 89 | TokenForUser = authResult.AccessToken; 90 | Expiration = authResult.ExpiresOn; 91 | } 92 | } 93 | 94 | return TokenForUser; 95 | } 96 | 97 | /// 98 | /// Signs the user out of the service. 99 | /// 100 | public static void SignOut() 101 | { 102 | foreach (var user in IdentityClientApp.Users) 103 | { 104 | IdentityClientApp.Remove(user); 105 | } 106 | graphClient = null; 107 | TokenForUser = null; 108 | } 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /CICDINSTRUCTIONS.md: -------------------------------------------------------------------------------- 1 | # Deploy custom policies from your Azure DevOps pipeline 2 | 3 | This guide shows how to use Microsoft Graph apis for managing custom policies to deploy custom policies as part of your Azure DevOps pipeline. 4 | 5 | ## Getting started 6 | 7 | ### Prerequisites 8 | 9 | This sample requires the following: 10 | 11 | * [Azure DevOps pipeline](https://azure.microsoft.com/en-us/services/devops/pipelines/) 12 | * [Azure AD B2C tenant](https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-get-started) 13 | 14 | 15 | ### Fundamentals 16 | The instructions use client credential flow to get a token. The token is then used to call Microsoft Graph apis. 17 | 18 | 19 | ### Create a web application in Azure AD 20 | 1. Sign in to the [Azure Portal](https://portal.azure.com/) using your Microsoft account. 21 | 1. Go to your Azure AD B2C tenant. you can do this by selecting book binding icon in top right corner portal. 22 | 1. Select Azure Active Directory blade in the portal. Form the left menu, select App registrations (Legacy). 23 | 1. From the command bar, select + icon which says 'New application registration'. 24 | 1. Enter configuration as suggested below and select 'Create' 25 | 1. Name :a name of your choice. Let's call it B2CDeployApp. 26 | 1. Application type : Web app/API 27 | 1. Sign-on URL : https://jwt.ms (you can choose any url of your choice). 28 | 29 | 1. After the app is created. Go to the app, select 'Settings' and then 'Required Permissions' from the menu. 30 | 1. Select 'Add'. And then 'Select an API' 31 | 1. Select 'Microsoft Graph' from the list and then select Create. 32 | 1. Select 'Select permissions'. From **APPLICATION PERMISSIONS**, check 'Read and write your organization's trust framework policies'. 33 | 1. Choose 'Select' at the bottom, and then 'Done'. 34 | 1. Select 'Grant permissions' to grant newly selected permissions consent to the app. 35 | 1. There will be a dialogue box, select 'Yes'. 36 | 37 | #### Create password for the new app. 38 | 1. In settings for the app, select 'Keys'. 39 | 1. Under 'Passwords' section, enter a description such as 'devopskey' and select 'Save'. 40 | 1. A value for the password will be shown, copy and paste it in a safe place. This is a sensitive piece of information. 41 | 1. Navigate to the overview page of the app, and copy the 'Application ID'. It will be used in next steps. 42 | 43 | ### Configure yor Azure DevOps git repository 44 | 1. Sign in to your Azure DevOps organization and navigate to your project. 45 | 1. In your project, navigate to the 'files' page. 46 | 1. Create a folder called 'B2CAssets' 47 | 1. Add your Azure AD B2C Policies here. 48 | 1. Create another folder with name Scripts. 49 | 1. Copy the PowerShell Script named 'DeployToB2c.ps1' from **this** sample to the newly created folder in your repo. 50 | 1. The script gets a token from Azure AD based on the config and then calls Microsoft Graph Api to upload the policy. 51 | 52 | ### Configure your Azure DevOps release pipeline 53 | 1. Sign in to your Azure DevOps organization and navigate to your project. 54 | 1. In your project, navigate to the 'Release' page under 'Pipelines'. Then choose the action to create a new pipeline. 55 | 1. Select 'Empty Job' at the top of navigation pane to choose a template. 56 | 1. In the next screen, enter a name for the stage such as 'DeployCustomPolicies' 57 | 1. Add an artifact to the pipeline, follow prompts and choose your repo. For this guide, the repo should be a git repo. 58 | 1. Switch to 'Variables' tab. 59 | 1. Add following variables 60 | 1. Name: clientId, Value: 'applicationId of the app you created earlier' 61 | 1. Name: clientSecret, Value: 'password of the app you created earlier'. 62 | - Please make sure to change variable type to 'Secret' by selecting the lock icon next to Value field. 63 | 1. Name: tenantId, Value: 'yourtenant.onmicrosoft.com' 64 | 65 | 1. Switch to Tasks tab 66 | 1. Select Agent job, and then select '+' to add a task to the Agent job. From right side search for 'PowerShell' and add it. There might be multiple 'PowerShell' tasks, such as Azure PowerShell etc. Please choose the one which says just 'PowerShell'. 67 | 1. Select newly added 'PowerShell Script' task. 68 | 1. Enter following values 69 | 1. Task Version: 1.* 70 | 1. Type : File Path 71 | 1. Script Path: '$(System.DefaultWorkingDirectory)/yourartifactalias/Scripts/DeployToB2C.ps1' 72 | - this is the path to the script file you had added earlier. 73 | 1. Arguments: -ClientID $(clientId) -ClientSecret $(clientSecret) -TenantId $(tenantId) -PolicyId B2C_1A_TrustFrameworkBase -PathToFile $(System.DefaultWorkingDirectory)/yourartifactalias/B2CAssets/TrustFrameworkBase.xml 74 | - Choose policy names and file path accordingly. 75 | - Your artifact alias can be found at the bottom of your Artifacts settings as "Source alias" looks like this: _NameOfMyProject 76 | 1. Save the pipeline. 77 | 1. Create release and run the pipeline. You can check results if the deployment was successful. 78 | 1. This sample uploads only one policy. Feel free to modify the PowerShell script to upload more policies. Or you can add the same task with different parameters multiple times. 79 | 80 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/B2CPolicyClient.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F} 8 | Exe 9 | console_csharp_trustframeworkpolicy 10 | B2CPolicyClient 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\Microsoft.Graph.1.4.0\lib\net45\Microsoft.Graph.dll 37 | 38 | 39 | ..\packages\Microsoft.Graph.Core.1.5.0\lib\net45\Microsoft.Graph.Core.dll 40 | 41 | 42 | ..\packages\Microsoft.Identity.Client.1.1.0-preview\lib\net45\Microsoft.Identity.Client.dll 43 | 44 | 45 | ..\packages\Microsoft.OData.Client.6.11.0\lib\net40\Microsoft.OData.Client.dll 46 | 47 | 48 | ..\packages\Microsoft.OData.Core.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.OData.Core.dll 49 | 50 | 51 | ..\packages\Microsoft.OData.Edm.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.OData.Edm.dll 52 | 53 | 54 | ..\packages\Microsoft.OData.ProxyExtensions.1.0.35\lib\portable-net45+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10\Microsoft.OData.ProxyExtensions.dll 55 | 56 | 57 | ..\packages\Microsoft.Spatial.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.Spatial.dll 58 | 59 | 60 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | Designer 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /console-csharp-trustFrameworkPolicy/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | 7 | namespace console_csharp_trustframeworkpolicy 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | // validate parameters 14 | if (!CheckValidParameters(args)) 15 | return; 16 | 17 | HttpRequestMessage request = null; 18 | ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; 19 | 20 | try 21 | { 22 | // Login as global admin of the Azure AD B2C tenant 23 | UserMode.LoginAsAdmin(); 24 | 25 | // Graph client does not yet support trustFrameworkPolicy, so using HttpClient to make rest calls 26 | switch (args[0].ToUpper()) 27 | { 28 | case "LIST": 29 | // List all polcies using "GET /trustFrameworkPolicies" 30 | request = UserMode.HttpGet(Constants.TrustFrameworkPolicesUri); 31 | break; 32 | case "GET": 33 | // Get a specific policy using "GET /trustFrameworkPolicies/{id}" 34 | request = UserMode.HttpGetID(Constants.TrustFrameworkPolicyByIDUri, args[1]); 35 | break; 36 | case "CREATE": 37 | // Create a policy using "POST /trustFrameworkPolicies" with XML in the body 38 | string xml = System.IO.File.ReadAllText(args[1]); 39 | request = UserMode.HttpPost(Constants.TrustFrameworkPolicesUri, xml); 40 | break; 41 | case "UPDATE": 42 | // Update using "PUT /trustFrameworkPolicies/{id}" with XML in the body 43 | xml = System.IO.File.ReadAllText(args[2]); 44 | request = UserMode.HttpPutID(Constants.TrustFrameworkPolicyByIDUri, args[1], xml); 45 | break; 46 | case "DELETE": 47 | // Delete using "DELETE /trustFrameworkPolicies/{id}" 48 | request = UserMode.HttpDeleteID(Constants.TrustFrameworkPolicyByIDUri, args[1]); 49 | break; 50 | default: 51 | return; 52 | } 53 | 54 | Print(request); 55 | 56 | HttpClient httpClient = new HttpClient(); 57 | Task response = httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead); 58 | 59 | Print(response); 60 | } 61 | catch (Exception e) 62 | { 63 | Print(request); 64 | Console.WriteLine("\nError {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); 65 | } 66 | } 67 | 68 | public static bool CheckValidParameters(string[] args) 69 | { 70 | if (Constants.ClientIdForUserAuthn.Equals("ENTER_YOUR_CLIENT_ID") || 71 | Constants.Tenant.Equals("ENTER_YOUR_TENANT_NAME")) 72 | { 73 | Console.ForegroundColor = ConsoleColor.Red; 74 | Console.WriteLine("1. Open 'Constants.cs'"); 75 | Console.WriteLine("2. Update 'ClientIdForUserAuthn'"); 76 | Console.WriteLine("3. Update 'Tenant'"); 77 | Console.WriteLine(""); 78 | Console.WriteLine("See README.md for detailed instructions."); 79 | Console.WriteLine(""); 80 | Console.ForegroundColor = ConsoleColor.White; 81 | Console.WriteLine("[press any key to exit]"); 82 | Console.ReadKey(); 83 | return false; 84 | } 85 | 86 | if (args.Length <= 0) 87 | { 88 | Console.ForegroundColor = ConsoleColor.Red; 89 | Console.WriteLine("Please enter a command as the first argument."); 90 | Console.ForegroundColor = ConsoleColor.White; 91 | PrintHelp(args); 92 | return false; 93 | } 94 | 95 | switch (args[0].ToUpper()) 96 | { 97 | case "LIST": 98 | break; 99 | case "GET": 100 | if (args.Length <= 1) 101 | { 102 | PrintHelp(args); 103 | return false; 104 | } 105 | break; 106 | case "CREATE": 107 | if (args.Length <= 1) 108 | { 109 | PrintHelp(args); 110 | return false; 111 | } 112 | break; 113 | case "UPDATE": 114 | if (args.Length <= 2) 115 | { 116 | PrintHelp(args); 117 | return false; 118 | } 119 | break; 120 | case "DELETE": 121 | if (args.Length <= 1) 122 | { 123 | PrintHelp(args); 124 | return false; 125 | } 126 | break; 127 | case "HELP": 128 | PrintHelp(args); 129 | return false; 130 | default: 131 | Console.ForegroundColor = ConsoleColor.Red; 132 | Console.WriteLine("Invalid command."); 133 | Console.ForegroundColor = ConsoleColor.White; 134 | PrintHelp(args); 135 | return false; 136 | } 137 | return true; 138 | } 139 | 140 | public static void Print(Task responseTask) 141 | { 142 | responseTask.Wait(); 143 | HttpResponseMessage response = responseTask.Result; 144 | 145 | if (!response.IsSuccessStatusCode) 146 | { 147 | Console.WriteLine("Error Calling the Graph API HTTP Status={0}", response.StatusCode); 148 | } 149 | 150 | Console.WriteLine(response.Headers); 151 | Task taskContentString = response.Content.ReadAsStringAsync(); 152 | taskContentString.Wait(); 153 | Console.WriteLine(taskContentString.Result); 154 | } 155 | 156 | public static void Print(HttpRequestMessage request) 157 | { 158 | if (request != null) 159 | { 160 | Console.Write(request.Method + " "); 161 | Console.WriteLine(request.RequestUri); 162 | Console.WriteLine(""); 163 | } 164 | } 165 | 166 | private static void PrintHelp(string[] args) 167 | { 168 | string appName = "B2CPolicyClient"; 169 | Console.ForegroundColor = ConsoleColor.White; 170 | Console.WriteLine("- Square brackets indicate optional arguments"); 171 | Console.WriteLine(""); 172 | Console.ForegroundColor = ConsoleColor.Cyan; 173 | Console.WriteLine("List : {0} List", appName); 174 | Console.WriteLine("Get : {0} Get [PolicyID]", appName); 175 | Console.WriteLine(" : {0} Get B2C_1A_PolicyName", appName); 176 | Console.WriteLine("Create : {0} Create [RelativePathToXML]", appName); 177 | Console.WriteLine(" : {0} Create policytemplate.xml", appName); 178 | Console.WriteLine("Update : {0} Update [PolicyID] [RelativePathToXML]", appName); 179 | Console.WriteLine(" : {0} Update B2C_1A_PolicyName updatepolicy.xml", appName); 180 | Console.WriteLine("Delete : {0} Delete [PolicyID]", appName); 181 | Console.WriteLine(" : {0} Delete B2C_1A_PolicyName", appName); 182 | Console.WriteLine("Help : {0} Help", appName); 183 | Console.ForegroundColor = ConsoleColor.White; 184 | Console.WriteLine(""); 185 | 186 | if (args.Length == 0) 187 | { 188 | Console.WriteLine("[press any key to exit]"); 189 | Console.ReadKey(); 190 | } 191 | } 192 | } 193 | } 194 | --------------------------------------------------------------------------------