Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user claims inside ASP Core 2 method without Authorize attribute?

I have a method on an API that can be accessed anonymously. I want to use resource authorization to determine if the user has access. If the object is "public" than it can be accessed by anyone (including anonymous users). If the object is "private" than it can only be viewed by logged in users. This logic works fine if I have an authorize attribute on the method, but if not the User has no claims even when they are logged in.

Is there a way to get the user's claims in a method without an Authorize attribute?

Method looks like this:

    [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();
    }
like image 577
Lin Meyer Avatar asked Oct 28 '25 14:10

Lin Meyer


1 Answers

The solution was actually very simple, adding [AllowAnonymous] and [Authorize] did the trick.

like image 130
Lin Meyer Avatar answered Oct 30 '25 04:10

Lin Meyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!