- Azure account with an active subscription. Create an account for free.
- Azure Active Directory tenant
- .NET Core SDK 3.1+
- Visual Studio 2019 or Visual Studio Code
Step 1: Register the application
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- For Name, enter a name for your application. For example, enter AspNetCoreWebApi-Quickstart. Users of your app will see this name, and you can change it later.
- Select Register.
- Under Manage, select Expose an API > Add a scope. For Application ID URI, accept the default by selecting Save and continue, and then enter the following details:
- Scope name: access_as_user
- Who can consent?: Admins and users
- Admin consent display name: Access AspNetCoreWebApi-Quickstart
- Admin consent description: Allows the app to access AspNetCoreWebApi-Quickstart as the signed-in user.
- User consent display name: Access AspNetCoreWebApi-Quickstart
- User consent description: Allow the application to access AspNetCoreWebApi-Quickstart on your behalf.
- State: Enabled
- Select Add scope to complete the scope addition.
Step 2: Download the ASP.NET Core project
Step 3: Configure the ASP.NET Core project
- Extract the .zip archive into a folder near the root of your drive. For example, extract into C:\Azure-Samples.
- We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows.
- Open the solution in the webapi folder in your code editor.
- Open the appsettings.json file and modify the following code:
"ClientId": "Enter_the_Application_Id_here","TenantId": "Enter_the_Tenant_Info_Here"
- Replace Enter_the_Application_Id_here with the application (client) ID of the application that you registered in the Azure portal. You can find the application (client) ID on the app's Overview page.
- Replace Enter_the_Tenant_Info_Here with one of the following:
- If your application supports Accounts in this organizational directory only, replace this value with the directory (tenant) ID (a GUID) or tenant name (for example, contoso.onmicrosoft.com). You can find the directory (tenant) ID on the app's Overview page.
- If your application supports Accounts in any organizational directory, replace this value with organizations.
- If your application supports All Microsoft account users, leave this value as common.
- For this quickstart, don't change any other values in the appsettings.json file.
How the sample works
Startup class
public void ConfigureServices(IServiceCollection services){services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration, "AzureAd");}
// The runtime calls this method. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){// more codeapp.UseAuthentication();app.UseAuthorization();// more code}
Protecting a controller, a controller's method, or a Razor page
You can protect a controller or controller methods by using the [Authorize] attribute. This attribute restricts access to the controller or methods by allowing only authenticated users. An authentication challenge can be started to access the controller if the user isn't authenticated.
namespace webapi.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
Validation of scope in the controller
The code in the API verifies that the required scopes are in the token by using HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
namespace webapi.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
// The web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API
static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
// some code here
}
}
}
Thanks 😀