.Net Core 2.0 Web API OpenIddict 授权:重定向到索引而不是返回 json 数据



所以,问题是当我在我的 api 控制器上使用 AuthorizeAttribute 时,它会停止以预期的方式工作。

当我调用 getAllUsers 操作时,标识以某种方式重定向到索引,而不是以 json 格式返回用户.html然后我在 Angular 客户端应用程序中收到 json 解析器错误,因为 html 不是可以解析的有效 json 数据。

升级到 Asp.Net Core 2.0后,这种情况开始发生。

我想也许我必须在我的创业.cs或程序.cs中改变一些东西。但是我不知道是什么。

我已经遵循了OpenIddict上新Core 2.0的刷新令牌示例,一切似乎都很好。

所以这是我的代码...

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

用户控制器.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 方法中放置断点,它永远不会被命中。不知何故,由于授权,应用程序重定向到索引.html之前。

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

顺便说一下,身份验证正在工作。我能够获取令牌,但无法授权控制器访问。

解决了。就像我想象的那样需要一些配置。只需添加 DefaultAuthenticateScheme 选项,如下所示:

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

添加此内容后,控制器开始正常工作,生成 json 数据而不是索引.html。

最新更新