dotnet core IdentityModel 使用作用域保护端点

dotnet core IdentityModel protect endpoints using scopes

概述

我有一个使用 OAuth2Introspection 保护的 dotNet 网站 API。授权由网络 API 验证第三方发布的参考令牌来确定。 Web API 有多个端点,其中一些端点需要不同的范围(例如读取与读写)。

问题

如何使用范围来控制对每个端点的访问?我希望能够执行以下操作:

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();
        }
    }
}

这是通过定义一个或多个策略,然后将范围映射到来完成的。你的政策。然后,您使用 [Authorize(Policy = 'name')] 标记将策略分配给端点。有关详细信息,请参阅 this article