Chapter 3 - jayharris/workshop-oidc GitHub Wiki
Chapter 3: API Resources
3.1: Create an API project
# From ./
dotnet new webapi --name ApiResource --output ./src/ApiResource/
dotnet sln add ./src/ApiResource/ApiResource.csproj
3.2: Turn off HTTPS
Do not do this for production. Because this is a workshop about Identity Server and not SSL configuration, we will disable HTTPS and leave that for another workshop.
ApiResource\Startup.cs
within the Configure
method
//app.UseHttpsRedirection();
3.3: Change the HTTP and HTTPS port numbers
The default template sets the HTTPS and HTTP ports to 5001 and 5000, respectively, but these are already in use by the Identity Provider. Change them to 5011 and 5010.
ApiResource/Properties/launchSettings.json
within the Profiles.ApiResource
values settings.
"ApiResource": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "https://localhost:5011;http://localhost:5010",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
3.4: Run the API. Access the generated controller.
The project template includes a sample Values
controller. This will be used to test.
# From: ./src/ApiResoure/
dotnet run
Load the site in a browser, accessing its Values
url at http://localhost:5010/api/values. A successful request will return ["value1","value2"]
.
Stop execution after you have completed testing.
3.5: Install IdentityServer NuGet Packages
# From ./src/ApiResource
dotnet add package IdentityServer4.AccessTokenValidation
3.6: Add a new Resource configuration to the Identity Provider
Add an API Resource to IdentityProvider\IdentityConfiguration.cs
within the GetApis
method:
new ApiResource("apiResource", "API Resource")
3.7: Configure Middleware and Services
Configure Authentication services.
ApiResource/Startup.cs
within ConfigureServices
method:
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "apiResource";
});
Enable Authentication middleware.
ApiResource/Startup.cs
within Configure
method, add app.UseAuthentication()
above the MVC middleware configuration:
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
3.8: Add Authorize attribute to existing Controller
The Values controller was generated by default within the project template.
ApiResource\Controllers\ValuesController.cs
using Microsoft.AspNetCore.Authorization;
ApiResource\Controllers\ValuesController.cs
adding an attribute to the class
[Authorize]
3.9: Run the API. Access the generated controller.
The project template includes a sample Values
controller. This will be used to test.
# From: ./src/ApiResoure/
dotnet run
Load the site in a browser, accessing its Values
url at http://localhost:5010/api/values. A successful request will return HTTP 401 Unauthorized; your API is now a protected resource.
Stop execution after you have completed testing.