gpt4 book ai didi

ASP.NET 核心 Web API 授权属性返回 404 错误并强制重定向

转载 作者:行者123 更新时间:2023-12-03 15:58:22 26 4
gpt4 key购买 nike

我有包含以下项目的 asp.net core 2.0 解决方案:

  • 数据:EF 代码
  • 的类库
  • OAuth:作为 IdentityServer4 代码
  • 的 Web 应用程序项目
  • Api:对于我创建为空 Web 项目的 API

  • 现在 OAuth 项目配置了 aspnetidentity 并且它工作正常,我能够在身份验证后获取 token ,这是它的启动代码:
    public void ConfigureServices(IServiceCollection services)
    {
    // connect with normal database
    services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
    .GetConnectionString("MCareConnection")));

    services.AddIdentity<User, IdentityRole>()
    .AddEntityFrameworkStores<MCareContext>()
    .AddDefaultTokenProviders();


    services.AddMvc();

    // IS configurations database
    var dbConnectionString = Configuration.GetConnectionString("MCareConnection.OAuth");
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

    services.AddIdentityServer()
    .AddConfigurationStore(options =>
    {
    options.ConfigureDbContext = builder =>
    builder.UseSqlServer(dbConnectionString,
    sql => sql.MigrationsAssembly(migrationsAssembly));
    })

    .AddOperationalStore(options =>
    {
    options.ConfigureDbContext = builder =>
    builder.UseSqlServer(dbConnectionString,
    sql => sql.MigrationsAssembly(migrationsAssembly));
    })

    .AddAspNetIdentity<User>()
    .AddDeveloperSigningCredential();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    DatabaseInitializer.InitializeDatabase(app);

    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }

    app.UseIdentityServer();

    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
    }

    现在是 API 项目的问题,每当我打开任何授权的 Controller /操作时,它都会给我 404 错误,这是启动代码:
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddDbContext<MCareContext>(options => options.UseSqlServer(Configuration
    .GetConnectionString("MCareConnection")));

    services.AddIdentity<User, IdentityRole>()
    .AddEntityFrameworkStores<MCareContext>()
    .AddDefaultTokenProviders();

    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(options =>
    {
    options.Authority = "http://localhost:60415";
    options.ApiName = "mCareApi";
    options.RequireHttpsMetadata = false;
    });

    services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    loggerFactory.AddConsole();

    app.UseAuthentication();

    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
    }

    如果我在上面的代码上关闭这部分:
    //services.AddIdentity<User, IdentityRole>()
    //.AddEntityFrameworkStores<MCareContext>()
    //.AddDefaultTokenProviders();

    然后授权属性按预期工作,但另一个新问题,它显示 500 内部服务器错误,每当我打开任何 Controller ,如 AccountController 期望 UserManager userManager 在其构造函数

    InvalidOperationException: Unable to resolve service for type Microsoft.AspNetCore.Identity.UserManager`1[MCare.Data.Entities.User] while attempting to activate MCare.Api.Controllers.AccountsController



    我想知道为什么会发生这种情况以及如何解决这个问题,而不是将 IdentityServer4 项目与 API 项目混合在一起,因为我看到的所有项目都将它们混合在一个项目中。

    最佳答案

    当 DefaultChallengeScheme 遇到可能导致 404 的授权属性时,它是否可能重定向到不存在的页面,例如登录页面?

    尝试将默认质询设置为返回未授权的 Jwt 架构。

    services.AddAuthentication(options =>
    {
    options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddIdentityServerAuthentication(options =>
    {
    options.Authority = "http://localhost:60415";
    options.ApiName = "mCareApi";
    options.RequireHttpsMetadata = false;
    });

    或者您可以通过为事件提供处理程序来尝试我在下面的文章中提到的方法。
    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(options =>
    {
    options.JwtBearerEvents = new JwtBearerEvents
    {
    OnChallenge = context =>
    {
    context.Response.StatusCode = 401;
    return Task.CompletedTask;
    }
    };
    options.Authority = "http://localhost:60415";
    options.ApiName = "mCareApi";
    options.RequireHttpsMetadata = false;
    });

    关于ASP.NET 核心 Web API 授权属性返回 404 错误并强制重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46669881/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com