Authorize admission to REST APIs with OAuth 2.0

Azure DevOps Services

Note

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

Authenticate your web app users for REST API access, so your app doesn't continue to inquire for usernames and passwords. Azure DevOps Services uses the OAuth 2.0 protocol to qualify your app for a user and generate an access token. Use this token when you call the Balance APIs from your application.

When you lot telephone 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# case of the overall flow, come across vsts-auth-samples.

Register your app

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

Make certain you select the scopes that your application needs, and so employ the same scopes when you authorize your app. If you registered your app using the preview APIs, re-annals because the scopes that y'all used are now deprecated.

When Azure DevOps Services presents the say-so approval page to your user, information technology uses your company name, app name, and descriptions. Information technology also uses the URLs for your company web site, app website, and terms of service and privacy statements.

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

When Azure DevOps Services asks for a user's authorisation, and the user grants information technology, the user's browser gets redirected to your authority callback URL with the authorization lawmaking. The callback URL must be a secure connection (https) to transfer the code back to the app. It must exactly friction match the URL registered in your app. If information technology doesn't, a 400 mistake page is displayed instead of a page request the user to grant authorization to your app.

When yous register your app, the application settings folio displays.

Applications settings shown for your app.

Call the dominance URL and pass your app ID and authorized scopes when you want to have a user authorize your app to access their organisation. Call the admission token URL when you lot want to go an access token to call an Azure DevOps Services REST API.

The settings for each app that you register are available from your contour 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 potency URL.

              https://app.vssps.visualstudio.com/oauth2/authorize         ?client_id={app ID}         &response_type={Exclamation}         &country={land}         &telescopic={telescopic}         &redirect_uri={callback URL}                          
Parameter Type Notes
client_id GUID The ID assigned to your app when it was registered.
response_type cord Assertion
state string Can be whatever value. Typically a generated cord value that correlates the callback with its associated authorization. request.
telescopic cord Scopes registered with the app. Space separated. Run into available scopes.
redirect_uri URL Callback URL for your app. Must exactly lucifer the URL registered with the app.

Azure DevOps Services asks your user to authorize your app. It handles hallmark, and then calls you back with an authorization lawmaking, if the user approves the authorization.

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'due south browser to your callback URL, including a short-lived authorization code and the land value provided in the potency URL:

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

Get an access and refresh token for the user

Now you 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 - qualify app

Header Value
Content-Type application/10-www-form-urlencoded
Content-Length Calculated string length of the request trunk (see the post-obit instance)
              Content-Type: application/10-www-form-urlencoded Content-Length: 1322                          

HTTP request body - authorize app

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

Supplant 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 lawmaking query parameter to your callback URL
  • {2}: callback URL registered with the app

C# instance to form the request trunk - authorize app

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

Response - authorize app

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

Of import

Securely persist the refresh_token and so your app doesn't need to prompt the user to authorize again. Access tokens expire relatively rapidly and shouldn't exist persisted.

Use the admission 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:

              Become https://dev.azure.com/myaccount/myproject/_apis/build-release/builds?api-version=three.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 caused in the dominance flow to get a new access token. Information technology's similar the original procedure for exchanging the dominance lawmaking for an access and refresh token.

URL - refresh token

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

HTTP asking headers - refresh token

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

HTTP request torso - 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}                          

Supervene upon the placeholder values in the previous sample asking body:

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

Response - refresh token

              {     "access_token": { admission 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 } }                          

Of import

A new refresh token gets issued for the user. Persist this new token and use it the side by side time you need to larn a new access token for the user.

Scopes

Important

Scopes only enable access to REST APIs and select Git endpoints. SOAP API admission isn't supported.

Category Scope Name Description
Agent Pools vso.agentpools Amanuensis Pools (read) Grants the power to view tasks, pools, queues, agents, and currently running or recently completed jobs for agents.
vso.agentpools_manage Agent Pools (read, manage) Grants the power to manage pools, queues, and agents.
vso.environment_manage Enviroment (read, manage) Grants the ability to manage pools, queues, agents, and environments.
Analytics vso.analytics Analytics (read) Grants the power to query analytics data.
Audit Log vso.auditlog Audit Log (read) Grants the ability to read the auditing log to users.
Build vso.build Build (read) Grants the power to access build artifacts, including build results, definitions, and requests, and the power to receive notifications nearly build events via service hooks.
vso.build_execute Build (read and execute) Grants the ability to admission 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 Lawmaking (read) Grants the power to read source code and metadata virtually commits, changesets, branches, and other version command artifacts. Likewise grants the ability to search lawmaking and get notified most version control events via service hooks.
vso.code_write Code (read and write) Grants the power to read, update, and delete source code, admission metadata about commits, changesets, branches, and other version control artifacts. Besides grants the power to create and manage pull requests and lawmaking 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 most 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 (total) Grants full access to source lawmaking, 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 simply admission to licensing entitlements endpoint to get account entitlements.
vso.memberentitlementmanagement MemberEntitlement Management (read) Grants the ability to read users, their licenses likewise as projects and extensions they can admission.
vso.memberentitlementmanagement_write MemberEntitlement Management (write) Grants the ability to manage users, their licenses equally well as projects and extensions they tin 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 past installed extensions.
vso.extension.data_write Extension information (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, grouping, scope, and group membership information.
vso.graph_manage Graph (manage) Grants the power to read user, group, telescopic 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 power to read, write, and manage identities and groups.
Load Test vso.loadtest Load test (read) Grants the power 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 exam runs, and read metadata including test results and APM artifacts.
Motorcar Grouping vso.machinegroup_manage Deployment group (read, manage) Provides ability to manage deployment group and agent pools.
Market vso.gallery Marketplace Grants read admission to public and individual items and publishers.
vso.gallery_acquire Marketplace (acquire) Grants read access and the ability to acquire items.
vso.gallery_publish Marketplace (publish) Grants read admission and the ability to upload, update, and share items.
vso.gallery_manage Marketplace (manage) Grants read access and the power 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 admission to consequence metadata, including filterable field values.
vso.notification_manage Notifications (manage) Provides read, write, and management admission to subscriptions and read access to result 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 private subscriptions.
Packaging vso.packaging Packaging (read) Grants the power 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 Projection and team (read) Grants the ability to read projects and teams.
vso.project_write Project and team (read and write) Grants the power to read and update projects and teams.
vso.project_manage Projection and squad (read, write and manage) Grants the power 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 environs.
vso.release_execute Release (read, write and execute) Grants the power 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 power to read, update, and delete release artifacts, including releases, release definitions and release environment, and the power 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 power to read and query service endpoints.
vso.serviceendpoint_manage Service Endpoints (read, query and manage) Grants the power to read, query, and manage service endpoints.
Settings vso.settings Settings (read) Grants the power 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 power to read and write symbols.
vso.symbols_manage Symbols (read, write and manage) Grants the ability to read, write, and manage symbols.
Chore Groups vso.taskgroups_read Task Groups (read) Grants the ability to read job groups.
vso.taskgroups_write Chore 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 power to read team dashboard information.
vso.dashboards_manage Team dashboards (manage) Grants the ability to manage team dashboard information.
Test Management vso.examination Test management (read) Grants the power to read test plans, cases, results and other examination direction 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 Say-so Tokens Grants the ability to manage delegated potency tokens to users.
vso.tokenadministration Token Assistants Grants the ability to manage (view and revoke) existing tokens to organisation administrators.
User Profile vso.contour User profile (read) Grants the power to read your profile, accounts, collections, projects, teams, and other top-level organizational artifacts.
vso.profile_write User profile (write) Grants the power 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. Besides 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 Piece of work items (read) Grants the power to read work items, queries, boards, area and iterations paths, and other piece of work particular tracking related metadata. Likewise grants the ability to execute queries, search work items and to receive notifications nigh 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 surface area and iterations paths other work item tracking related metadata, execute queries, and to receive notifications about work particular events via service hooks.
vso.work_full Work items (full) Grants full access to work items, queries, backlogs, plans, and work detail tracking metadata. As well provides the power to receive notifications about piece of 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 admission their organization, they authorize it for those scopes. Requesting the authorization passes the aforementioned scopes that you registered.

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

Samples

Y'all 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: Tin I use OAuth with my mobile phone app?

A: No. Azure DevOps Services only supports the web server flow, so there'southward no way to implement OAuth, as y'all tin't securely store the app secret.

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

A: Brand sure that y'all handle the following conditions:

  • If your user denies your app access, no authority code gets returned. Don't use the potency code without checking for denial.
  • If your user revokes your app's potency, the admission token is no longer valid. When your app uses the token to access data, a 401 fault returns. Request authorization over again.

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

A: Yeah. Azure DevOps Services now allows localhost in your callback URL. Ensure you lot use https://localhost as the beginning of your callback URL when you annals your app.

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

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

Q: I get an HTTP 401 mistake when I utilise an OAuth-based access token, only a PAT with the same scope works fine. Why?

A: Verify that Third-party awarding admission via OAuth hasn't been disabled by your organisation'southward admin at https://dev.azure.com/{your-org-proper noun}/_settings/organizationPolicy.

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

Q: Can I utilize OAuth with the SOAP endpoints and Residue 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 detail details with Work items - Get piece of work detail REST API:

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

To get the attachments details, you demand to add together the post-obit parameter to the URL:

              $aggrandize=all                          

With the results, y'all become the relations property. There yous can notice the attachments URL, and within the URL you can discover the ID. For example:

              $url = https://dev.azure.com/{system}/{project}/_apis/wit/workitems/434?$expand=all&api-version=5.0  $workItem = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json  $divide = ($workitem.relations.url).Split('/')  $attachmentId = $divide[$split.count - 1]  # Result: 1244nhsfs-ff3f-25gg-j64t-fahs23vfs                          
  • Choosing the right authentication method
  • Default permissions and admission for Azure DevOps