Authorize access to REST APIs with OAuth 2.0

Authenticate your web app's users to access the REST APIs so that your app doesn't have to keep asking for their usernames and passwords. Azure DevOps Services uses the OAuth 2.0 protocol to authorize your app for a user and generate an access token. Use this token when you call the REST APIs from your app.

First, you'll register your web app and get an app ID from Azure DevOps Services. Using that app ID, you'll send your users to Azure DevOps Services to authorize your app to access their organizations there. Once they've done that, you'll use that authorization to get an access token for that user. When you call Azure DevOps Services APIs on behalf of that user, you'll use that user's access token. Access tokens expire, so you'll also need to refresh the access token if it's expired.

Process to get authorization

For a C# example of the overall flow, see vsts-auth-samples

Register your app

Go to (https://app.vsaex.visualstudio.com/app/register) to register your app.

Make sure you select the scopes that your application needs, and then use the exact same scopes when you authorize your app. If you registered your app using the preview APIs, you'll want to re-register because the scopes that you used are now deprecated.

When Azure DevOps Services presents the authorization approval page to your user, it will use your company name, and app name and descriptions, along with the URLs for your company's web site, your app's website, and your terms of service and privacy statements, like this.

Visaul Studio Online authorization page with your company and app information

When you call Azure DevOps Services to ask for a user's authorization, and the user grants it, Azure DevOps Services will redirect the user's browser to your authorization callback URL with the authorization code for that authorization. The callback URL must be a secure connection (https) to transfer the code back to the app. It must exactly match the URL registered in your app. If it doesn't, a 400 error page is displayed instead of a page asking the user to grant authorization to your app.

When your register your app, the application settings page is displayed.

Application settings for your app

You'll call the authorization URL and pass your app ID and authorized scopes when you want to have a user authorize your app to access their organization. You'll call the access token URL when you want to get an access token to call an Azure DevOps Services REST API.

The settings for each app that you register are available from your profile (https://app.vssps.visualstudio.com/profile/view).

Authorize your app

If your user hasn't yet authorized your app to access their organization, call the authorization URL.

https://app.vssps.visualstudio.com/oauth2/authorize
        ?client_id={app ID}
        &response_type=Assertion
        &state={state}
        &scope={scope}
        &redirect_uri={callback URL}
Parameter Type Notes
client_id GUID The ID assigned to your app when it was registered
response_type string Assertion
state string Can be any value. Typically a generated string value that correlates the callback with its associated authorization request.
scope string Scopes registered with the app. Space separated. See available scopes.
redirect_uri URL Callback URL for your appp. This must exactly match the URL registered with the app

Azure DevOps Services will ask your user to authorize your app. It will handle authentication and then call you back with an authorization code, if the user approves the authorization.

Add a link or button to your site that navigates the user to the Azure DevOps Services authorization endpoint:

https://app.vssps.visualstudio.com/oauth2/authorize
        ?client_id=88e2dd5f-4e34-45c6-a75d-524eb2a0399e
        &response_type=Assertion
        &state=User1
        &scope=vso.work%20vso.code_write
        &redirect_uri=https://fabrikam.azurewebsites.net/myapp/oauth-callback


Azure DevOps Services will ask the user to authorize your app.

Assuming the user accepts, Azure DevOps Services will redirect the user's browser to your callback URL, including a short-lived authorization code and the state value provided in the authorization URL:

https://fabrikam.azurewebsites.net/myapp/oauth-callback
        ?code={authorization code}
        &state=User1

Get an access and refresh token for the user

Now use the authorization code to request an access token (and refresh token) for the user. This requires your service making a service-to-service HTTP request to Azure DevOps Services.

URL

POST https://app.vssps.visualstudio.com/oauth2/token

HTTP request headers

Header Value
Content-Type application/x-www-form-urlencoded
Content-Length Calculated string length of the request body (see below)
Content-Type: application/x-www-form-urlencoded
Content-Length: 1322

HTTP request body

client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}


Replace the placeholder values in the sample request body above:

  • {0}: URL encoded client secret acquired when the app was registered
  • {1}: URL encoded "code" provided via the code query parameter to your callback URL
  • {2}: callback URL registered with the app

C# example to form the request body

public string GenerateRequestPostData(string appSecret, string authCode, string callbackUrl)
{
   return String.Format("client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}",
               HttpUtility.UrlEncode(appSecret),
               HttpUtility.UrlEncode(authCode),
               callbackUrl
        );
}

Response

{
    "access_token": { access token for the user },
    "token_type": { type of token },
    "expires_in": { time in seconds that the token remains valid },
    "refresh_token": { refresh token to use to acquire a new access token }
}


Important: securely persist the refresh_token so your app does not need to prompt the user authorize again. Access tokens expire relatively quickly and should not be persisted.

Use the access token

To use an access token, include it as a bearer token in the Authorization header of your HTTP request:

Authorization: Bearer {access_token}

For example, the HTTP request to get recent builds for a project:

GET https://dev.azure.com/myaccount/myproject/_apis/build-release/builds?api-version=3.0
Authorization: Bearer {access_token}

Refresh an expired access token

If a user's access token expires, you can use the refresh token acquired in the authorization flow to get a new access token. This process is similar to the original process for exchanging the authorization code for an access token and refresh token.

URL

POST https://app.vssps.visualstudio.com/oauth2/token

HTTP request headers

Header Value
Content-Type application/x-www-form-urlencoded
Content-Length Calculated string length of the request body (see below)
Content-Type: application/x-www-form-urlencoded
Content-Length: 1654

HTTP request body

client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=refresh_token&assertion={1}&redirect_uri={2}


Replace the placeholder values in the sample request body above:

  • {0}: URL encoded client secret acquired when the app was registered
  • {1}: URL encoded refresh token for the user
  • {2}: callback URL registered with the app

Response

{
    "access_token": { access token for this user },
    "token_type": { type of token },
    "expires_in": { time in seconds that the token remains valid },
    "refresh_token": { new refresh token to use when the token has timed out }
}


Important: a new refresh token will be issued for the user. Persist this new token and use it the next time you need to acquire a new access token for the user.

Scopes

IMPORTANT: Scopes only enable access to REST APIs and select Git endpoints. SOAP API access is not supported.

Category Scope Name Description
Agent Pools vso.agentpools Agent Pools (read) Grants the ability to view tasks, pools, queues, agents, and currently running or recently completed jobs for agents.
vso.agentpools_manage Agent Pools (read, manage) Grants the ability to manage pools, queues, and agents.
Build vso.build Build (read) Grants the ability to access build artifacts, including build results, definitions, and requests, and the ability to receive notifications about build events via service hooks.
vso.build_execute Build (read and execute) Grants the ability to access build artifacts, including build results, definitions, and requests, and the ability to queue a build, update build properties, and the ability to receive notifications about build events via service hooks.
Code vso.code Code (read) Grants the ability to read source code and metadata about commits, changesets, branches, and other version control artifacts. Also grants the ability to search code and get notified about version control events via service hooks.
vso.code_write Code (read and write) Grants the ability to read, update, and delete source code, access metadata about commits, changesets, branches, and other version control artifacts. Also grants the ability to create and manage pull requests and code reviews and to receive notifications about version control events via service hooks.
vso.code_manage Code (read, write, and manage) Grants the ability to read, update, and delete source code, access metadata about commits, changesets, branches, and other version control artifacts. Also grants the ability to create and manage code repositories, create and manage pull requests and code reviews, and to receive notifications about version control events via service hooks.
vso.code_full Code (full) Grants full access to source code, metadata about commits, changesets, branches, and other version control artifacts. Also grants the ability to create and manage code repositories, create and manage pull requests and code reviews, and to receive notifications about version control events via service hooks. Also includes limited support for Client OM APIs.
vso.code_status Code (status) Grants the ability to read and write commit and pull request status.
Entitlements vso.entitlements Entitlements (Read) Provides read only access to licensing entitlements endpoint to get account entitlements.
vso.memberentitlementmanagement MemberEntitlement Management (read) Grants the ability to read users, their licenses as well as projects and extensions they can access.
vso.memberentitlementmanagement_write MemberEntitlement Management (write) Grants the ability to manage users, their licenses as well as projects and extensions they can access.
Extensions vso.extension Extensions (read) Grants the ability to read installed extensions.
vso.extension_manage Extensions (read and manage) Grants the ability to install, uninstall, and perform other administrative actions on installed extensions.
vso.extension.data Extension data (read) Grants the ability to read data (settings and documents) stored by installed extensions.
vso.extension.data_write Extension data (read and write) Grants the ability to read and write data (settings and documents) stored by installed extensions.
Graph & identity vso.graph Graph (read) Grants the ability to read user, group, scope, and group membership information.
vso.graph_manage Graph (manage) Grants the ability to read user, group, scope and group membership information, and to add users, groups, and manage group memberships.
vso.identity Identity (read) Grants the ability to read identities and groups.
vso.identity_manage Identity (manage) Grants the ability to read, write, and manage identities and groups.
Load Test vso.loadtest Load test (read) Grants the ability to read your load test runs, test results, and APM artifacts.
vso.loadtest_write Load test (read and write) Grants the ability to create and update load test runs, and read metadata including test results and APM artifacts.
Machine Group vso.machinegroup_manage Deployment group (read, manage) Provides ability to manage deployment group and agent pools.
Marketplace vso.gallery Marketplace Grants read access to public and private items and publishers.
vso.gallery_acquire Marketplace (acquire) Grants read access and the ability to acquire items.
vso.gallery_publish Marketplace (publish) Grants read access and the ability to upload, update, and share items.
vso.gallery_manage Marketplace (manage) Grants read access and the ability to publish and manage items and publishers.
Notifications vso.notification Notifications (read) Provides read access to subscriptions and event metadata, including filterable field values.
vso.notification_write Notifications (write) Provides read and write access to subscriptions and read access to event metadata, including filterable field values.
vso.notification_manage Notifications (manage) Provides read, write, and management access to subscriptions and read access to event metadata, including filterable field values.
vso.notification_diagnostics Notifications (diagnostics) Provides access to notification-related diagnostic logs and provides the ability to enable diagnostics for individual subscriptions.
Packaging vso.packaging Packaging (read) Grants the ability to read feeds and packages.
vso.packaging_write Packaging (read and write) Grants the ability to create and read feeds and packages.
vso.packaging_manage Packaging (read, write, and manage) Grants the ability to create, read, update, and delete feeds and packages.
Project and Team vso.project Project and team (read) Grants the ability to read projects and teams.
vso.project_write Project and team (read and write) Grants the ability to read and update projects and teams.
vso.project_manage Project and team (read, write and manage) Grants the ability to create, read, update, and delete projects and teams.
Release vso.release Release (read) Grants the ability to read release artifacts, including releases, release definitions and release environment.
vso.release_execute Release (read, write and execute) Grants the ability to read and update release artifacts, including releases, release definitions and release envrionment, and the ability to queue a new release.
vso.release_manage Release (read, write, execute and manage) Grants the ability to read, update, and delete release artifacts, including releases, release definitions and release envrionment, and the ability to queue and approve a new release.
Security vso.security_manage Security (manage) Grants the ability to read, write, and manage security permissions.
Service Connections vso.serviceendpoint Service Endpoints (read) Grants the ability to read service endpoints.
vso.serviceendpoint_query Service Endpoints (read and query) Grants the ability to read and query service endpoints.
vso.serviceendpoint_manage Service Endpoints (read, query and manage) Grants the ability to read, query, and manage service endpoints.
Symbols vso.symbols Symbols (read) Grants the ability to read symbols.
vso.symbols_write Symbols (read and write) Grants the ability to read and write symbols.
vso.symbols_manage Symbols (read, write and manage) Grants the ability to read, write, and manage symbols.
Task Groups vso.taskgroups_read Task Groups (read) Grants the ability to read task groups.
vso.taskgroups_write Task Groups (read, create) Grants the ability to read and create task groups.
vso.taskgroups_manage Task Groups (read, create and manage) Grants the ability to read, create and manage taskgroups.
Team Dashboard vso.dashboards Team dashboards (read) Grants the ability to read team dashboard information.
vso.dashboards_manage Team dashboards (manage) Grants the ability to manage team dashboard information.
Test Management vso.test Test management (read) Grants the ability to read test plans, cases, results and other test management related artifacts.
vso.test_write Test management (read and write) Grants the ability to read, create, and update test plans, cases, results and other test management related artifacts.
Tokens vso.tokens Delegated Authorization Tokens Grants the ability to manage delegated authorization tokens to users.
vso.tokenadministration Token Administration Grants the ability to manage (view and revoke) existing tokens to organization administrators.
User Profile vso.profile User profile (read) Grants the ability to read your profile, accounts, collections, projects, teams, and other top-level organizational artifacts.
vso.profile_write User profile (write) Grants the ability to write to your profile.
Variable Groups vso.variablegroups_read Variable Groups (read) Grants the ability to read variable groups.
vso.variablegroups_write Variable Groups (read, create) Grants the ability to read and create variable groups.
vso.variablegroups_manage Variable Groups (read, create and manage) Grants the ability to read, create and manage variable groups.
Wiki vso.wiki Wiki (read) Grants the ability to read wikis, wiki pages and wiki attachments. Also grants the ability to search wiki pages.
vso.wiki_write Wiki (read and write) Grants the ability to read, create and updates wikis, wiki pages and wiki attachments.
Work Items vso.work Work items (read) Grants the ability to read work items, queries, boards, area and iterations paths, and other work item tracking related metadata. Also grants the ability to execute queries, search work items and to receive notifications about work item events via service hooks.
vso.work_write Work items (read and write) Grants the ability to read, create, and update work items and queries, update board metadata, read area and iterations paths other work item tracking related metadata, execute queries, and to receive notifications about work item events via service hooks.
vso.work_full Work items (full) Grants full access to work items, queries, backlogs, plans, and work item tracking metadata. Also provides the ability to receive notifications about work item events via service hooks.

When you register your app, you'll use scopes to indicate which permissions in Azure DevOps Services your app will require. When your users authorize your app to access their organization, they'll authorize it for those scopes. When you call to request that authorization, you'll pass the same scopes that you registered.

Samples

You can find a C# sample that implements OAuth to call Azure DevOps Services REST APIs in our C# OAuth GitHub Sample.

Q&A

Q: Can I use OAuth with my phone app?

A: No. Right now, Azure DevOps Services only support the web server flow, so there's no supported way to implement OAuth for Azure DevOps Services from an app like a phone app, since there's no way to securely store the app secret.

Q: What errors or special conditions do I need to handle in my code?

A: Make sure that you handle these conditions:

  1. If your user denies your app access, no authorization code is returned. Don't use the authorization code without checking for that.
  2. If your user revokes your app's authorization, the access token is no longer valid. When your app uses the token to access data, a 401 error is returned. You'll have to request authorization again.

Q: I want to debug my web app locally. Can I use localhost for the callback URL when I register my app?

A: Azure DevOps Services does not allow localhost to be the hostname in your callback URL. You can edit the hosts file on your local computer to map a hostname to 127.0.0.1. Then use this hostname when you register your app. Or, you can deploy your app when testing to a Microsoft Azure website to be able to debug and use HTTPS for the callback URL.

Q: I get an HTTP 400 error when I try to get an access token. What might be wrong?

A: Check that you set the content type to application/x-www-form-urlencoded in your request header.

Q: Can I use OAuth with the SOAP endpoints as well as the REST APIs?

A: No. OAuth is only supported in the REST APIs at this point.