.Net Core / Identity Server - 是否可以 AllowAnonymous 但只能来自我的客户端?

.Net Core / Identity Server - Is it possible to AllowAnonymous but only from my client?

我设置了 REST API 和 IdentityServer。我希望能够在 API 的客户端中显示项目而无需登录。但是,我还想保护我的 API 免受不属于我的外部客户端的影响。是否可以允许匿名但只能来自我的客户?

[HttpGet]
[AllowAnonymous]
public List<Item> GetItems()
{
    return new List<Item> { "item1", "item2" };
}

使用解决方案编辑 正如 Tore Nestenius 所提到的,我将授权类型从 Code 更改为 CodeAndClientCredentials,并将 Authorize 属性添加到我的控制器,以便只有我的客户端可以访问它。

控制器:

[HttpGet]
[Authorize]
public List<Item> GetItems()
{
    return new List<Item> { "item1", "item2" };

Identity Server 4 配置文件:

public static IEnumerable<Client> Clients =>
    new Client[] 
    {
        new Client
        {
            ClientId = "postman-api",
            AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
            ClientSecrets =
            {
                    new Secret("secret".Sha256())
            },
        }
    };
}

原来这是由 CORS 处理的。

    public void ConfigureServices(IServiceCollection services)
    {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder => builder
                        .WithOrigins("yourURL")
                        .AllowAnyMethod());
            })
     }

CORS只对来自浏览器的请求起作用,如果是非浏览器应用发出请求,那么CORS将不会被涉及。

如果您使用 [AllowAnonymous],则任何客户端都可以访问该 API 端点。您可以为一般事物创建单独的客户端,也许使用客户端凭据流程,以便客户端可以进行身份​​验证,获取自己的令牌而无需任何用户参与。