授权 API returns HTML 当控制器被击中而不是内容时

Authorized API returns HTML when the controller is hit and not the content

我在身份服务器项目中有一个非常基本的 Web API 控制器:

namespace Project.IDP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet]
        public IActionResult Test()
        {
            return Ok("Test");
        }
    }
}

如果我通过 Postman 调用此控制器,我会收到 OK 响应 200 和内容 'Test',太棒了。

但是,如果我添加授权属性,我会收到 HTML! HTML 是身份服务器的登录页面。但是,我已经授权并且正在请求中传递访问令牌(全部通过邮递员)

namespace Project.IDP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class MyController : ControllerBase
    {
        [HttpGet]
        public IActionResult Test()
        {
            return Ok("Test");
        }
    }
}

我的客户端是这样设置的:

新客户 { ClientId="m2m", ClientName = "机器2机器客户端", AllowedGrantTypes = GrantTypes.ClientCredentials, 客户机密 = { 新秘密(“秘密”.Sha256()) }, 允许范围 = { IdentityServerConstants.LocalApi.ScopeName, “myapi.mi_test” } },

API是这样的:

    new ApiResource[]
    {
        new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
        new ApiResource("myapi", "My API" )
        {
            Scopes = new List<Scope>
            {
                new Scope("myapi.mi_test", "MI Access")
            }
        }
    };

在我的启动中 class 已经尝试过:

    services.AddLocalApiAuthentication();

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:31101";
                options.ApiName = "myapi";
            });

但我无法让它工作,我错过了什么?

我有一个类似的设置,唯一的区别是您需要在授权属性中指定特定的授权策略。在您的“MyController”中,将您的 Authorize 属性更改为:

[Authorize(LocalApi.PolicyName)]

此要求显示在 IdenityServer 文档中:

https://identityserver4.readthedocs.io/en/latest/topics/add_apis.html