Skip to content

Commit 4f59a64

Browse files
committed
updating samples for VSTS exposed as a resource
1 parent 91721ff commit 4f59a64

File tree

4 files changed

+158
-11
lines changed

4 files changed

+158
-11
lines changed

AdalJsSample/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# ADAL JS Sample
2+
3+
The [Azure Active Directory Authentication Library (ADAL)](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-libraries) enables client application developers to authenticate cloud users and obtain access tokens for API usage.
4+
5+
## Sample Application
6+
7+
This buildable sample will walk you through the steps to create single page javascript application which uses ADAL to authenticate a user via an interactive prompt and all VSTS known information associated with the signed in identity.
8+
9+
To run this sample you will need:
10+
* Http-server. You can download [NPM http server](https://www.npmjs.com/package/http-server) if you need one.
11+
* An Azure Active Directory (AAD) tenant. If you do not have one, follow these [steps to set up an AAD](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-howto-tenant)
12+
* A user account in your AAD tenant
13+
* A VSTS account backed by your AAD tenant where your user account has access. If you have an existing VSTS account not connected to your AAD tenant follow these [steps to connect you AAD tenant to your VSTS account](https://www.visualstudio.com/en-us/docs/setup-admin/team-services/manage-organization-access-for-your-account-vs)
14+
15+
## Step 1: Clone or download vsts-auth-samples repository
16+
17+
From a shell or command line:
18+
```no-highlight
19+
git clone https://github.com/Microsoft/vsts-auth-samples.git
20+
```
21+
22+
## Step 2: Register the sample application with you Azure Active Directory tenant
23+
24+
1. Sign in to the [Azure Portal](https://portal.azure.com).
25+
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you wish to register your application.
26+
3. On the left hand navigation menu, select `Azure Active Directory`.
27+
4. Click on `App registrations` and select `New application regirstation` from the top bar.
28+
5. Enter a `name` for you application, ex. "Adal JS sample", choose `Web app/API` for `application type`, and enter `http://localhost:8080` for the `Redirect URI`. Finally click `create` at the bottom of the screen.
29+
6. Save the `Application ID` from your new application registration. You will need it later in this sample.
30+
7. Grant Permissions for VSTS. Click `Required permissions` -> `add` -> `1 Select an API` -> type in and select `Microsoft Visual Studio Team Services` -> check the box for `Have full access to...` -> click `Save` -> click `Grant Permissions` -> click `Yes`.
31+
32+
## Step 3: Run the sample
33+
34+
1. Open `index.html` in [Visual Studio Code](https://code.visualstudio.com/download?wt.mc_id=adw-brandcore-editor-slink-downloads&gclid=EAIaIQobChMItJndsOXH1QIVFJR-Ch3uTgMREAAYASABEgLb2vD_BwE) or another text editor or IDE.
35+
2. Inside `index.html` there is a section of `Input Vars` you can update to run the sample:
36+
* `clientId` - (Required) update this with the `application id` you saved from `portal.azure.com`
37+
* `replyUri` - (optional) update this if you are hosting `index.html` at an address other than `hottp://localhost:8080`
38+
* `vstsApi` - (optional) update this if you would like to the sample to run a different VSTS API
39+
* `vstsResourceId` - Do not change this value. It is used to receive VSTS ADAL authentication tokens
40+
3. Navigate to the ADAL JS sample in cloned repo `vsts-auth-samples/AdalJsSample/` and start your http-server which will serve `index.hmtl` at `http://localhost:8080`.
41+
4. Navigate to `http://localhost:8080`. Sign in with a user account from your AAD tenant which has access to at least 1 VSTS account. Displayed should be all VSTS known identity infromation about the signed in user account.
42+
43+
44+
45+

AdalJsSample/index.html

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>VSTS Autentication ADAL.JS Sample</title>
5+
<meta charset="utf-8" />
6+
<style type="text/css">body { font-family: Tahoma; padding: 3em; }</style>
7+
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
8+
</head>
9+
<body>
10+
<p>
11+
VSTS Authentication - ADAL.JS Sample
12+
</p>
13+
<p>
14+
<a href="#" onclick="authContext.login(); return false;">Log in</a> |
15+
<a href="#" onclick="authContext.logOut(); return false;">Log out</a>
16+
</p>
17+
<p id="username"></p>
18+
<pre id="api_response"></pre>
19+
20+
<script type="text/javascript">
21+
// Set up ADAL
22+
var authContext = new AuthenticationContext({
23+
clientId: '57c5c51c-2036-433a-befa-ebefc7f10689',//Update with your app regirstion's Application ID
24+
postLogoutRedirectUri: 'http://localhost:8080' //Where you return upon signout
25+
});
26+
// Make an AJAX request to the VSTS REST API and print the response as JSON.
27+
var getCurrentUser = function (access_token) {
28+
document.getElementById('api_response').textContent = 'Calling API...';
29+
var xhr = new XMLHttpRequest();
30+
xhr.open('GET', 'https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0', true); //API called with ADAL token
31+
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
32+
xhr.onreadystatechange = function () {
33+
if (xhr.readyState === 4 && xhr.status === 200) {
34+
// Parse Successful Response
35+
document.getElementById('api_response').textContent =
36+
JSON.stringify(JSON.parse(xhr.responseText), null, ' ');
37+
} else {
38+
// Handle Error
39+
document.getElementById('api_response').textContent =
40+
'ERROR:\n\n' + xhr.responseText;
41+
}
42+
};
43+
xhr.send();
44+
}
45+
if (authContext.isCallback(window.location.hash)) {
46+
// Handle redirect after token requests
47+
authContext.handleWindowCallback();
48+
var err = authContext.getLoginError();
49+
if (err) {
50+
// TODO: Handle errors signing in and getting tokens
51+
document.getElementById('api_response').textContent =
52+
'ERROR:\n\n' + err;
53+
}
54+
} else {
55+
// If logged in, get access token and make an API request
56+
var user = authContext.getCachedUser();
57+
if (user) {
58+
document.getElementById('username').textContent = 'Signed in as: ' + user.userName;
59+
document.getElementById('api_response').textContent = 'Getting access token...';
60+
61+
// Get an access token to the Microsoft Graph API
62+
authContext.acquireToken(
63+
'499b84ac-1321-427f-aa17-267ca6975798',
64+
function (error, token) {
65+
if (error || !token) {
66+
// TODO: Handle error obtaining access token
67+
document.getElementById('api_response').textContent =
68+
'ERROR:\n\n' + error;
69+
return;
70+
}
71+
// Use the access token
72+
getCurrentUser(token);
73+
}
74+
);
75+
} else {
76+
document.getElementById('username').textContent = 'Not signed in.';
77+
}
78+
}
79+
</script>
80+
</body>
81+
</html>

ManagedClientConsoleAppSample/Program.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Linq;
44
using System.Net.Http;
55
using System.Net.Http.Headers;
6+
using System.Threading;
67

78
namespace ManagedClientConsoleAppSample
89
{
@@ -11,10 +12,11 @@ class Program
1112
//============= Config [Edit these with your settings] =====================
1213
internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
1314
// internal const string vstsCollectioUrl = "http://myserver:8080/tfs/DefaultCollection" alternate URL for a TFS collection
15+
internal const string clientId = "0fa17cf4-f75c-4185-ab9a-7c5ea47ca073"; //change to your app registration's Application ID
16+
internal const string replyUri = "http://localhost:8080"; //change to your app registration's reply URI.
1417
//==========================================================================
1518

16-
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Static value to target VSTS. Do not change
17-
internal const string clientId = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1"; //VS ClientId. Please use this instead of your app's clientId
19+
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Constant value to target VSTS. Do not change
1820

1921
public static void Main(string[] args)
2022
{
@@ -23,7 +25,7 @@ public static void Main(string[] args)
2325
try
2426
{
2527
//PromptBehavior.RefreshSession will enforce an authn prompt every time. NOTE: Auto will take your windows login state if possible
26-
result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), new PlatformParameters(PromptBehavior.Always)).Result;
28+
result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Always)).Result;
2729
Console.WriteLine("Token expires on: " + result.ExpiresOn);
2830

2931
var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
@@ -32,7 +34,7 @@ public static void Main(string[] args)
3234
catch (UnauthorizedAccessException)
3335
{
3436
// If the token has expired, prompt the user with a login prompt
35-
result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), new PlatformParameters(PromptBehavior.Always)).Result;
37+
result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Always)).Result;
3638
}
3739
catch (Exception ex)
3840
{
@@ -78,6 +80,7 @@ private static void ListProjects(AuthenticationHeaderValue authHeader)
7880
{
7981
Console.WriteLine("\tSuccesful REST call");
8082
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
83+
Thread.Sleep(10000);
8184
}
8285
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
8386
{

ManagedClientConsoleAppSample/README.md

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,43 @@ The [Azure Active Directory Authentication Library (ADAL)](https://docs.microsof
66

77
This buildable sample will walk you through the steps to create a client-side console application which uses ADAL to authenticate a user via an interactive prompt and return a list of all projects inside a selected VSTS account.
88

9+
To run this sample you will need:
10+
* Visual Studio 2017
11+
* An Azure Active Directory (AAD) tenant. If you do not have one, follow these [steps to set up an AAD](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-howto-tenant)
12+
* A user account in your AAD tenant
13+
* A VSTS account backed by your AAD tenant where your user account has access. If you have an existing VSTS account not connected to your AAD tenant follow these [steps to connect you AAD tenant to your VSTS account](https://www.visualstudio.com/en-us/docs/setup-admin/team-services/manage-organization-access-for-your-account-vs)
14+
915
## Step 1: Clone or download vsts-auth-samples repository
1016

1117
From a shell or command line:
1218
```no-highlight
1319
git clone https://github.com/Microsoft/vsts-auth-samples.git
1420
```
1521

16-
## Step 2: Install and configure ADAL (optional)
22+
## Step 2: Register the sample application with you Azure Active Directory tenant
23+
24+
1. Sign in to the [Azure Portal](https://portal.azure.com).
25+
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you wish to register your application.
26+
3. On the left hand navigation menu, select `Azure Active Directory`.
27+
4. Click on `App registrations` and select `New application regirstation` from the top bar.
28+
5. Enter a `name` for you application, ex. "Adal native app sample", choose `Native` for `application type`, and enter `http://localhost:8080` for the `Redirect URI`. Finally click `create` at the bottom of the screen.
29+
6. Save the `Application ID` from your new application registration. You will need it later in this sample.
30+
7. Grant Permissions for VSTS. Click `Required permissions` -> `add` -> `1 Select an API` -> type in and select `Microsoft Visual Studio Team Services` -> check the box for `Have full access to...` -> click `Save` -> click `Grant Permissions` -> click `Yes`.
31+
32+
## Step 3: Install and configure ADAL (optional)
1733

1834
Package: `Microsoft.Identity.Model.Clients.ActiveDirectory` has already been installed and configured in the sample, but if you are adding to your own project you will need to [install and configure it yourself](https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory).
1935

20-
## Step 3: Run the sample
36+
## Step 4: Run the sample
2137

22-
1. Navigate to the ADAL C# sample in cloned repo `vsts-auth-samples/ManagedClientConsoleAppSample/`
23-
2. Use [Nuget package restore](https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore) to ensure you have all dependencies installed
24-
3. Open the solution file `ManagedClientConsoleAppSample.csproj` in [Visual Studio 2017](https://www.visualstudio.com/downloads/)
38+
1. Navigate to the ADAL C# sample in cloned repo `vsts-auth-samples/ManagedClientConsoleAppSample/`.
39+
2. Use [Nuget package restore](https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore) to ensure you have all dependencies installed.
40+
3. Open the solution file `ManagedClientConsoleAppSample.sln` in [Visual Studio 2017](https://www.visualstudio.com/downloads/).
2541
4. Open CS file `Program.cs` and there is a section with input values to change at the top of the class:
26-
* `vstsCollectionUrl` - Mutable value. This is the url to your VSTS/TFS collection, e.g. http://myaccount.visualstudio.com for VSTS or http://myserver:8080/tfs/DefaultCollection for TFS.
27-
5. Build and run solution. After running you should see a list of all projects inside of myaccount.
42+
* `vstsCollectionUrl` - update this with the url to your VSTS/TFS collection, e.g. http://myaccount.visualstudio.com for VSTS or http://myserver:8080/tfs/DefaultCollection for TFS.
43+
* `clientId` - update this with the `application id` you saved from `portal.azure.com`
44+
* `replyUri` - we have set this to `http://localhost:8080`, but please update it as necessary for your own app.
45+
5. Build and run solution. After running you should see an interactive login prompt. Then after authentication and authorization, a list of all projects inside of your account.
2846

2947

3048

0 commit comments

Comments
 (0)