【问题标题】:.net core 5.0.2 and jwt => response 401 Unauthorized.net core 5.0.2 and jwt => response 401 Unauthorized
【发布时间】:2021-06-17 04:33:25
【问题描述】:

我正在关注带有 Web api 的身份服务器 4 的视频教程。 而且我不确定我什么时候出错了。

当我尝试使用不记名令牌调用 api 时,我得到 401 Unauthorized。 在上一步中,未经授权,我的 api 工作。

这是我的 TablesReach.API 项目中的 api 控制器:

...
namespace TablesReach.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly DataContext _context;

        public UsersController(DataContext context)
        {
            _context = context;
        }

        // GET: api/Users
        [HttpGet]
        public async Task<ActionResult<IEnumerable<User>>> GetUsers()
        {
            return await _context.Users.ToListAsync();
        }
...

这是我的 api 项目的 Startup.cs:

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(opts => 
                { 
                    opts.Authority = "http://localhost:5000";
                    opts.RequireHttpsMetadata = false;
                    opts.ApiName = "TablesReachApi";
                });

            services.AddDbContext<DataContext>(opts => opts.UseInMemoryDatabase("UNWDb"));

            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.UseAuthorization();

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

            app.UseAuthentication();
        }
    }

我的其他项目 TablesReach.IdentityServer 托管在 localhost:5000 而且我能够获得不记名令牌,所以我认为这个项目很好。 identityServer startup.cs 类:

 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.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiScopes(Config.GetAllApiResources())
                .AddInMemoryClients(Config.GetClients());
        }

        // 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();
            }
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //    app.UseHsts();
            //}
            //app.UseHttpsRedirection();
            //app.UseStaticFiles();

            //app.UseRouting();

            //app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllerRoute(
            //        name: "default",
            //        pattern: "{controller=Home}/{action=Index}/{id?}");
            //});

            app.UseIdentityServer();

        }
    }

和 Config.cs:

public class Config
    {
        public static IEnumerable<ApiScope> GetAllApiResources()
        {
            return new List<ApiScope>
            {
                new ApiScope("TablesReachApi", "Api for solution")
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "TablesReachApi" }
                }
            };
        }
    }

注意:当我从我的 api 控制器中删除注释 [Authorize] 时,我可以访问我的方法。

【问题讨论】:

    标签: asp.net-core asp.net-web-api identityserver4


    【解决方案1】:

    对于某些中间件,顺序很重要。例如,身份验证和授权不能按照您将它们放入 API 的顺序进行。微软有一些明确的文档供你阅读here..

    【讨论】:

    • 我仍然有 404 以及您提供的链接中的示例配置。
    • 嗯,404 和 401 不一样。所以,如果不是拼写错误,那么您现在面临的是路由问题,而不是未经授权的问题。
    猜你喜欢
    • 2020-07-02
    • 2019-06-20
    • 1970-01-01
    • 2015-03-13
    • 2020-07-05
    • 1970-01-01
    • 2018-08-06
    • 2022-12-22
    • 2019-01-04
    相关资源
    最近更新 更多