在双重身份验证类型asp.net core 2项目中的AllowAnonymous操作上始终为404状态代码

时间:2017-11-24 19:03:03

标签: asp.net asp.net-mvc asp.net-core-2.0

我有一个包含两个区域的ASP.NET Core 2项目,管理员 Api 。第一个(管理员)用cookie保护,第二个用JWT保护。这是在本教程之后创建的:https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2,一切都按预期工作。使用cookie验证效果很好,路由工作很好,api在发送不记名令牌时正确识别用户。

管理区域使用[Authorize]属性,而 Api 使用[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

尝试从邮递员(https://www.getpostman.com/)拨打POST: /Api/Auth/GetToken时出现问题,即使代码达到return BadRequest();return Unauthorized();,最终状态代码始终为404,除非凭据有效且调用return Ok();时。此操作位于具有[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]的控制器下,但该操作具有[AllowAnonymous]属性。当我从没有持票人令牌的邮递员调用此操作时,我可以调试代码,因此它仍然按预期工作到此处,但邮递员获得的返回状态代码不是预期的。

对我来说,看起来问题是关于错误发生的重定向,可能是OnLoginRedirect事件,但这是一个匿名操作,我将返回某些状态代码。这可能是什么问题?

AuthController中的动作代码:

public class AuthController : ApiBaseController
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IConfigurationRoot _config;

        public AuthController(
            UserManager<ApplicationUser> userManager, 
            SignInManager<ApplicationUser> signInManager,
            IConfigurationRoot config)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _config = config;
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetToken([FromBody] LoginDto dto)
        {
            if (dto == null) return BadRequest();
            if (!ModelState.IsValid) return BadRequest(ModelState);

            var user = await _userManager.FindByEmailAsync(dto.Email);

            if (user == null) return Unauthorized();

            var result = _signInManager.CheckPasswordSignInAsync(user, dto.Password, false);

            if (!result.Result.Succeeded) return Unauthorized();

            return Ok(GetTokensInfo(user));
        }`

ApiBaseController代码:

[Area("Api")]
[EnableCors("CorsPolicy")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public abstract class ApiBaseController : Controller
{ }`

更新:404仅在[HttpPost]次操作时发生。指定[HttpGet]属性时,所有属性都按预期工作。

UPDATE#2:评论此行:{Start}的配置方法时,app.UseStatusCodePagesWithReExecute("/error/{0}");一切正常。

1 个答案:

答案 0 :(得分:0)

最后找到了更新#2中发布的问题的根源。我现在要采用的最终解决方案是使用以下代码修改Startup.cs文件中的Configure方法:

app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), appBuilder =>
        {
            appBuilder.UseStatusCodePagesWithReExecute("/error/{0}");
        });