ASP.NET核心Web API授权属性返回404错误&强制重定向 [英] ASP.NET core Web API Authorize Attribute return 404 Error & force redirect

查看:125
本文介绍了ASP.NET核心Web API授权属性返回404错误&强制重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have asp.net core 2.0 solution which contains following projects:

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

现在OAuth项目已配置为aspnetidentity并且可以正常工作,我能够在身份验证后获取令牌,这是它的启动代码:

Now the OAuth project is configured with aspnetidentity and its working fine, I able to get the token after authentication, and this is the startup code for it:

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项目中出现问题,每当我打开任何授权的控制器/操作时,它都会给我404错误,这是启动代码:

Now the problem on the API project, whenever I open any authorized controller/action its give me 404 error, and this the startup code:

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();
}

如果我关闭以上代码的这一部分:

If I close this part on the above code:

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

然后,Authorize属性按预期工作,但是另一个新问题是,每当我打开任何诸如AccountController之类的希望在其构造函数上使用UserManager userManager的控制器时,它就会显示500个内部服务器错误

Then the Authorize attribute work as expected, but another new problem, it shows 500 internal server error, whenever I opened any controller like AccountController which expect UserManager userManager on its constructor

InvalidOperationException:无法解析类型的服务 Microsoft.AspNetCore.Identity.UserManager`1 [MCare.Data.Entities.User] 尝试激活MCare.Api.Controllers.AccountsController时

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项目混合在一起,因为我看到的所有项目都将它们混合在一个项目中.

I want to know why this is happening and how to solve this problem, without mixing IdentityServer4 project with the API project, because all the projects I have seen they mix both of them on one project.

推荐答案

DefaultChallengeScheme是否有可能在遇到可能导致404的authorize属性时重定向到不存在的页面(例如登录页面)?

Is it possible that DefaultChallengeScheme is redirecting to a page that does not exist such as a login page when it encounters the authorize attribute which could cause the 404?

尝试将默认质询设置为返回未经授权的Jwt模式.

Try setting the default challenge to the Jwt schema which returns not authorized.

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

或者您可以通过提供事件处理程序来尝试我在下面的文章中提到的方法.

Or you could try the method I mentioned in the article below by providing a handler for the event.

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错误&amp;强制重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆