首页 > 解决方案 > dotnet core IdentityModel 不会内省从第三方 IDaaS 发出的令牌

问题描述

概述

我有一个 dotnet Core Web 服务(即 dotnet new webapi),我想用第三方 IDaaS 服务发布的参考令牌来保护它。我在 ConfigureServices 中添加了IdentityModel.AspNetCore.OAuth2Introspection库以及必要的附加代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
       
    services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
            .AddOAuth2Introspection(options =>
            {
                options.ClientId = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx";
                options.ClientSecret = "xxxxxxx";
                options.IntrospectionEndpoint = "https://demo.verify.ibm.com/v1.0/endpoint/default/introspect";
            });       
}

无论我做什么,我都会不断收到来自 WebAPI 的 401 UNAUTHORIZED 响应。事实上,我什至没有看到 Web API 正在与 IDaaS 联系以验证承载令牌。

以下是 HTTP 跟踪:

GET /WeatherForecast HTTP/1.1
> Host: localhost:5001
> User-Agent: insomnia/2021.5.3
> Cookie: PD-S-SESSION-ID=1_2_1_K7PE6XKeEDKOkwioWpJxhxT8-Gdkz3TDgKXHgRIzMCKnQxYJ
> Authorization: Bearer **REMOVED**
> Accept: */*

* Mark bundle as not supporting multiuse

< HTTP/1.1 401 Unauthorized
< Date: Thu, 21 Oct 2021 17:15:14 GMT
< Server: Kestrel
< Content-Length: 0


* Connection #47 to host localhost left intact

针对以下端点:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace API.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [Authorize]
        public IEnumerable<WeatherForecast> Get()
        {
            

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

我想知道是否有人有做我想做的事情的经验?任何建议将不胜感激。

标签: c#.netasp.net-core

解决方案


问题是由于缺少app.UseAuthentication();管道的中间件注册。


推荐阅读