Search code examples
c#.net-coreoauth-2.0

dotnet core IdentityModel protect endpoints using scopes


Overview

I have a dotNet web API that is protected using OAuth2Introspection. Authorisation is determined by the web API validating third-party issued reference tokens. The web API has multiple endpoints, some of which require a different scope (e.g. read vs. readwrite).

Question(s)

How can I use scopes to control access to each endpoint? I was hoping to be able to do something like the following:

using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WeatherController : ControllerBase
    {
        private readonly ILogger<WeatherController> _logger;
        private readonly IConfiguration _config;

        public WeatherController(ILogger<WeatherController> logger, IConfiguration config)
        {
            _logger = logger;
            _config = config;
        }

        [HttpGet]
        [Authorize]
        [ScopeAuthorize("weather_read")]
        public ActionResult GetWeather()
        {
            return Ok();
        }

        [HttpPost]
        [Authorize]
        [ScopeAuthorize("weather_readwrite")]
        public ActionResult SetWeather(string weather)
        {
            return Ok();
        }
    }
}

Solution

  • This is done by defining one or more policies, then mapping the scopes to. your policies. Then, you assign the policy to the endpoint using the [Authorize(Policy = 'name')] tag. See this article for more details.