IdentityServer4 总是返回 401 Unauthorized 或 403 Forbidden

问题描述 投票:0回答:1

我是 IdentityServer4 的新手。我已经创建了一个 IdentityServer4 客户端,一个运行在 https://localhost:44311/ 的 IdentityServer4 范围。我使用 IdentityServer4 保护了一个示例 Weather API。当我运行

Program.cs
时,我收到一个授权令牌。我使用
client.SetBearerToken(tokenResponse.AccessToken);
设置此令牌,但是当我使用
await client.GetAsync($"https://localhost:44315/weatherforecast");
向 API 发送 GET 请求时,我收到 401 Unauthorized 或 403 Forbidden。我错过了什么?这是代码:

Startup.cs

namespace weatherapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication("Bearer", options =>
                {
                    options.ApiName = "weatherapi";
                    options.Authority = "https://localhost:44311/";
                });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

WeatherForecastController.cs

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 weatherapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    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]
        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();
        }
    }
}

Program.cs

using IdentityModel.Client;
using System.Text;

await SampleWeather();
//await SampleAdminApi();
async Task SampleWeather()
{
    using var client = new HttpClient();
    var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    {
        Address = "https://localhost:44311/connect/token",
        ClientId = "weatherapi",
        ClientSecret = "weatherapi",
        Scope = "weatherapi_scope",
        GrantType = "client_credentials"
    });

    if (tokenResponse.IsError)
    {
        throw new Exception("Unable to get token", tokenResponse.Exception);
    }

    client.SetBearerToken(tokenResponse.AccessToken);

    var response = await client.GetAsync($"https://localhost:44315/weatherforecast");
    var content = await response.Content.ReadAsStringAsync();

    Console.ReadLine();
}
c# asp.net-core asp.net-identity identityserver4 identity
1个回答
1
投票

因为它似乎是一个普通的 API,所以我会用 AddJwtBearer 替换 AddIdentityServerAuthentication(参见这个page

我还将在 AddJWtBearer 中将此标志设置为 true

opt.IncludeErrorDetails = true;

因为当你收到 401 错误时,你会在 WWW-Authenticate 标头中获得更多详细信息,如下所示:

HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"

为了补充这个答案,我写了一篇博客文章,详细介绍了这个主题: 解决 ASP.NET Core 中的 JwtBearer 身份验证问题

© www.soinside.com 2019 - 2024. All rights reserved.