如何在没有授权属性的情况下在 ASP Core 2 方法中获取用户声明?

Lin*_*yer 3 c# asp.net asp.net-authorization .net-core asp.net-core

我有一个可以匿名访问的 API 方法。我想使用资源授权来确定用户是否具有访问权限。如果对象是“公共的”,则任何人(包括匿名用户)都可以访问它。如果对象是“私有的”,则只能由登录用户查看。如果我在方法上有授权属性,则此逻辑工作正常,但如果没有,则即使用户登录也没有声明。

有没有办法在没有 Authorize 属性的方法中获取用户的声明?

方法如下所示:

    [HttpGet]
    [Route("name/{name}")]
    public async Task<IActionResult> Get(string name)
    {
        var activity = Repo.GetCommandLineActivity(name);
        if (activity == null)
        {
            return NotFound();
        }

        var isAuthed = await _authService.AuthorizeAsync(User, activity, new ViewIPublicPrivateRequirement());
        if (isAuthed.Succeeded)
        {
            return Ok(activity);
        }

        return Unauthorized();
    }
Run Code Online (Sandbox Code Playgroud)

Lin*_*yer 6

解决方案实际上非常简单,添加[AllowAnonymous]并解决问题[Authorize]

  • 我已经更改了属性标签,但用户的声明仍然不可用.. 运行 aspnet core 2.1 (2认同)