【发布时间】:2021-10-21 17:19:21
【问题描述】:
概述
我有一个 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 联系以验证 Bearer Token。
以下是 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();
}
}
}
我想知道是否有人有过我想做的事情的经验?任何建议将不胜感激。
【问题讨论】:
-
您的应用程序管道是否设置了
app.UseAuthentication();&app.UseAuthorization();? -
也可以尝试将
Authority设置为令牌服务的基地址,而不是IntrospectionEndpoint -
嗨@Killas,谢谢。添加 app.UseAuthentication();是什么解决了我的问题。请作为答案回复,以便我奖励您当之无愧的积分。
标签: c# .net asp.net-core