-
Notifications
You must be signed in to change notification settings - Fork 234
Web APIs
The Microsoft Identity Web library also enables web APIs to work with the Microsoft identity platform, enabling them to process access tokens for both work and school and Microsoft personal accounts, as well as B2C.
To enable the web API to accept tokens emitted by the Microsoft identity platform, replace this code in your web API's Startup.cs file:
using Microsoft.Identity.Web;
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
...
}
...
}
...with this code, using the AuthenticationBuilder
:
using Microsoft.Identity.Web;
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddProtectedWebApi(Configuration);
...
}
...
}
or with this code, using the services directly:
using Microsoft.Identity.Web;
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddProtectedWebApi(Configuration);
...
}
...
}
This method enables your web API to be protected using the Microsoft identity platform. This includes validating the token in all scenarios (single- and multi-tenant applications) in the Azure public and national clouds.
See also:
- ASP.NET Core Web API incremental tutorial chapter 1.1, Protect the web API
- Protected web API scenario overview in the Microsoft identity platform documentation, and related articles
If you want your web API to, moreover, call downstream web APIs, add the .AddProtectedWebApiCallsProtectedWebApi()
line, and then choose a token cache implementation, for example .AddInMemoryTokenCaches()
:
using Microsoft.Identity.Web;
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddProtectedWebApi(Configuration)
.AddProtectedWebApiCallsProtectedWebApi()
.AddInMemoryTokenCaches();
...
}
...
}
As with web apps, you can choose various token cache implementations.
If you're certain that your web API will need some specific scopes, you can optionally pass them as arguments to AddProtectedWebApiCallsProtectedWebApi
.
To enable your web API to call downstream APIs:
-
Add (as in web apps) a parameter of type
ITokenAcquisition
to the constructor of your controller. TheITokenAcquisition
service will be injected by dependency injection by ASP.NET Core. -
In your controller actions, verify that the token contains the scopes expected by the action. To do so, call the
VerifyUserHasAnyAcceptedScope
extension method on theHttpContext
. -
In your controller actions, call
ITokenAcquisition.GetAccessTokenForUserAsync
, passing the scopes for which to request a token.
The following code snippet shows how to combine these steps:
[Authorize]
public class HomeController : Controller
{
readonly ITokenAcquisition tokenAcquisition;
static string[] scopeRequiredByAPI = new string[] { "access_as_user" };
...
public async Task<IActionResult> Action()
{
HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByAPI);
string[] scopes = new []{"user.read"};
try
{
string accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(scopes);
// call the downstream API with the bearer token in the Authorize header
}
catch (MsalUiRequiredException ex)
{
_tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader(HttpContext, scopes, ex);
}
...
}
When your web API tries to get a token for the downstream API, the token acquisition service may throw a MsalUiRequiredException
. The MsalUiRequiredException
indicates that the user on the client calling the web API needs to perform additional actions, for example, multi-factor authentication.
Given that the web API isn't capable of performing such interaction itself, the exception needs to be passed to the client. To propagate the exception back to the client, catch the exception and call the ITokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader
method.
- Home
- Why use Microsoft Identity Web?
- Web apps
- Web APIs
- Minimal support for .NET FW Classic
- Logging
- Azure AD B2C limitations
- Samples
- Certificates
- Managed Identity as Federated Credential
- Federated Credentials from other Identity Provider
- Extensibility: Bring your own credential
- Web apps
- Web app samples
- Web app template
- Call an API from a web app
- Managing incremental consent and conditional access
- Web app troubleshooting
- Deploy to App Services Linux containers or with proxies
- SameSite cookies
- Hybrid SPA
- Web APIs
- Web API samples
- Web API template
- Call an API from a web API
- Token Decryption
- Web API troubleshooting
- web API protected by ACLs instead of app roles
- gRPC apps
- Azure Functions
- Long running processes in web APIs
- Authorization policies
- Generic API
- Customization
- Logging
- Calling graph with specific scopes/tenant
- Multiple Authentication Schemes
- Utility classes
- Setting FIC+MSI
- Mixing web app and web API
- Deploying to Azure App Services
- Azure AD B2C issuer claim support
- Performance
- specify Microsoft Graph scopes and app-permissions
- Integrate with Azure App Services authentication
- Ajax calls and incremental consent and conditional access
- Back channel proxys
- Client capabilities