Authorize access to REST APIs with OAuth 2.0

Azure DevOps Services

In this article, learn how to authenticate your web app users for REST API access, so your app doesn't continue to ask for usernames and passwords.

Note

The following guidance is intended for Azure DevOps Services users since OAuth 2.0 is not supported on Azure DevOps Server. Client Libraries are a series of packages built specifically for extending Azure DevOps Server functionality. For on-premises users, we recommend using Client Libraries, Windows Auth, or Personal Access Tokens (PATs) to authenticate on behalf of a user.

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 application.

When you call Azure DevOps Services APIs for that user, use that user's access token. Access tokens expire, so refresh the access token if it's expired.

Process to get authorization.

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

Note

You can register an application within your instance of Azure Active Directory (Azure AD). For more information, see OAuth 2.0 authentication with Azure AD and OpenID Connect protocol.

1. Register your app

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

  2. Select the scopes that your application needs, and then use the same scopes when you authorize your app. If you registered your app using the preview APIs, re-register because the scopes that you used are now deprecated.

  3. Select Create application.

    The application settings page displays.

    Screenshot showing Applications settings for your app.

    • When Azure DevOps Services presents the authorization approval page to your user, it uses your company name, app name, and descriptions. It also uses the URLs for your company web site, app website, and terms of service and privacy statements.

      Screenshot showing Visual Studio Codespaces authorization page with your company and app information.

    • When Azure DevOps Services asks for a user's authorization, and the user grants it, the user's browser gets redirected to your authorization callback URL with the authorization code. The callback URL must be a secure connection (https) to transfer the code back to the app and 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.

  4. 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. 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.

2. Authorize your app

  1. If your user hasn't yet authorized your app to access their organization, call the authorization URL. It calls you back with an authorization code, if the user approves the authorization.
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 app. Must exactly match the URL registered with the app.
  1. Add a link or button to your site that takes 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 asks the user to authorize your app.

Assuming the user accepts, Azure DevOps Services redirects 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

3. Get an access and refresh token for the user

Use the authorization code to request an access token (and refresh token) for the user. Your service must make a service-to-service HTTP request to Azure DevOps Services.

URL - authorize app

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

HTTP request headers - authorize app

Header Value
Content-Type application/x-www-form-urlencoded
Content-Type: application/x-www-form-urlencoded

HTTP request body - authorize app

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 previous sample request body:

  • {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 - authorize app

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 - authorize app

{
    "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 doesn't need to prompt the user to authorize again. Access tokens expire quickly and shouldn't be persisted.

4. 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 that they acquired in the authorization flow to get a new access token. It's like the original process for exchanging the authorization code for an access and refresh token.

URL - refresh token

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

HTTP request headers - refresh token

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

HTTP request body - refresh token

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 previous sample request body:

  • {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 - refresh token

{
    "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 gets 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 isn't 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.
vso.environment_manage Environment (read, manage) Grants the ability to manage pools, queues, agents, and environments.
Analytics vso.analytics Analytics (read) Grants the ability to query analytics data.
Auditing vso.auditlog Audit Log (read) Grants the ability to read the auditing log to users.
vso.auditstreams_manage Audit Streams (read) Grants the ability to manage auditing streams to users.
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.
Connected Server vso.connected_server Connected Server Grants the ability to access endpoints needed from an on-prem connected server.
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.
Pipeline Resources vso.pipelineresources_use Pipeline Resources (use) Grants the ability to approve a pipeline's request to use a protected resource: agent pool, environment, queue, repository, secure files, service connection, and variable group.
vso.pipelineresources_manage Pipeline Resources (use and manage) Grants the ability to manage a protected resource or a pipeline's request to use a protected resource: agent pool, environment, queue, repository, secure files, service connection, and variable group.
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 environment, 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 environment, and the ability to queue and approve a new release.
Secure Files vso.securefiles_read Secure Files (read) Grants the ability to read secure files.
vso.securefiles_write Secure Files (read, create) Grants the ability to read and create secure files.
vso.securefiles_manage Secure Files (read, create, and manage) Grants the ability to read, create, and manage secure files.
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.
Settings vso.settings Settings (read) Grants the ability to read settings.
vso.settings_write Settings (read and write) Grants the ability to create and read settings.
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.
Threads vso.threads_full PR threads Grants the ability to read and write to pull request comment threads.
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 (read, write, and manage) Grants full access to work items, queries, backlogs, plans, and work item tracking metadata, including process template imports. Also provides the ability to receive notifications about work item events via service hooks.

Register your app and use scopes to indicate which permissions in Azure DevOps Services that your app requires. When your users authorize your app to access their organization, they authorize it for those scopes. Requesting the authorization passes the same scopes that you registered.

For more information, see Create work item tracking/attachments.

Samples

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

Frequently asked questions (FAQs)

Q: Can I use OAuth with my mobile phone app?

A: No. Azure DevOps Services only supports the web server flow, so there's no way to implement OAuth, as you can't 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 the following conditions:

  • If your user denies your app access, no authorization code gets returned. Don't use the authorization code without checking for denial.
  • 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 returns. 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: Yes. Azure DevOps Services now allows localhost in your callback URL. Ensure you use https://localhost as the beginning of your callback URL when you register your app.

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: I get an HTTP 401 error when I use an OAuth-based access token, but a PAT with the same scope works fine. Why?

A: Verify that Third-party application access via OAuth hasn't been disabled by your organization's admin at https://dev.azure.com/{your-org-name}/_settings/organizationPolicy.

In this scenario, the flow to authorize an app and generate an access token works, but all REST APIs return only an error, such as TF400813: The user "<GUID>" is not authorized to access this resource.

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

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

Q: How can I get attachments detail for my work item using Azure DevOps REST APIs?

A: First, get the work item details with Work items - Get work item REST API:

GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}

To get the attachments details, you need to add the following parameter to the URL:

$expand=all

With the results, you get the relations property. There you can find the attachments URL, and within the URL you can find the ID. For example:

$url = https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/434?$expand=all&api-version=5.0

$workItem = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json

$split = ($workitem.relations.url).Split('/')

$attachmentId = $split[$split.count - 1]

# Result: 1244nhsfs-ff3f-25gg-j64t-fahs23vfs