.Net Core 2.0 Web API OpenIddict Authorization: เปลี่ยนเส้นทางไปยังดัชนีแทนที่จะส่งคืนข้อมูล json

ดังนั้น ปัญหาคือเมื่อฉันใช้ AuthorizeAttribute ที่ด้านบนของตัวควบคุม api มันจะหยุดทำงานตามที่คาดไว้

เมื่อฉันเรียกใช้การดำเนินการ getAllUsers แทนที่จะส่งคืนผู้ใช้ในรูปแบบ json Identity จะเปลี่ยนเส้นทางไปที่ index.html จากนั้นฉันได้รับข้อผิดพลาด json parser ในแอปไคลเอ็นต์ Angular ของฉัน เนื่องจาก html ไม่ใช่ข้อมูล json ที่ถูกต้องที่สามารถแยกวิเคราะห์ได้

สิ่งนี้เริ่มเกิดขึ้นหลังจากอัปเกรดเป็น Asp.Net Core 2.0

ฉันคิดว่าบางทีฉันอาจต้องเปลี่ยนแปลงบางอย่างใน Startup.cs หรือ Program.cs ของฉัน แต่ฉันไม่สามารถเข้าใจได้ว่าอะไร

ฉันได้ติดตามตัวอย่าง Refresh Token บน OpenIddict สำหรับ Core 2.0 ใหม่และทุกอย่างดูเหมือนจะโอเค

นี่คือรหัสของฉัน ...

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => {
            options.UseSqlServer(Configuration.GetConnectionString("LocalDB"))
                .UseOpenIddict();
        });
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IRoleRepository, RoleRepository>();
        services.AddScoped<IManadRepository, ManadRepository>();
        services.AddScoped<IManadRubricaRepository, ManadRubricaRepository>();
        services.AddScoped<IManadSistemaRepository, ManadSistemaRepository>();
        services.AddScoped<IRestituicaoRepository, RestituicaoRepository>();
        services.AddTransient<ApplicationDbSeedData>();

        services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddOpenIddict(options =>
        {
            options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
            options.AddMvcBinders();
            options.EnableTokenEndpoint("/connect/token");
            options.AllowPasswordFlow();
            options.AllowRefreshTokenFlow();

            if (!_env.IsProduction())
                options.DisableHttpsRequirement();
        });

        // Add framework services.
        services.AddMvc();

        services.AddAuthentication()
            .AddOAuthValidation();

        services.AddAuthorization();

        services.AddTransient<IMailSender, MailjetSender>();

        services.AddScoped<IManadParser, ManadParser>();
    }

public void Configure(IApplicationBuilder app, ApplicationDbSeedData dbDataSeeder)
    {        
        if (_env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });

        dbDataSeeder.EnsureSeedData().Wait();
    }

UsersController.cs

[Route("api/[controller]")]
[Authorize]
public class UsersController : Controller
{
    [HttpGet]
    [Authorize(Roles = "Administrador")]
    public IActionResult GetAllUsers()
    {
        try
        {
            var result = _repository.GetAllUsers();  

            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to get all users: {ex}");

            return BadRequest(ex.Message);
        }
    }
}

ถ้าฉันใส่เบรกพอยต์ในวิธี GetAllUsers มันจะไม่ถูกโจมตีเลย เนื่องจากได้รับอนุญาต แอปพลิเคชันจึงเปลี่ยนเส้นทางไปที่ index.html ก่อนหน้านี้

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

อย่างไรก็ตาม การรับรองความถูกต้องกำลังทำงานอยู่ ฉันสามารถรับโทเค็นได้ แต่ไม่สามารถให้สิทธิ์การเข้าถึงคอนโทรลเลอร์ได้


person Jackson Mourão    schedule 20.08.2017    source แหล่งที่มา


คำตอบ (1)


แก้ได้แล้ว แค่ต้องการการกำหนดค่าเล็กน้อยเหมือนที่ฉันคิด เพียงเพิ่มตัวเลือก DefaultAuthenticateScheme ดังนี้:

services.AddAuthentication(options => options.DefaultAuthenticateScheme = OAuthValidationDefaults.AuthenticationScheme)
            .AddOAuthValidation();

หลังจากเพิ่มสิ่งนี้ คอนโทรลเลอร์ก็เริ่มทำงานอย่างถูกต้อง ทำให้ได้ข้อมูล json ไม่ใช่ index.html

person Jackson Mourão    schedule 21.08.2017