如何在没有Authorize属性的ASP Core 2方法中获取用户声明? [英] How to get user claims inside ASP Core 2 method without Authorize attribute?

查看:38
本文介绍了如何在没有Authorize属性的ASP Core 2方法中获取用户声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有没有一种方法可以在没有Authorize属性的情况下获取用户的主张?

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

方法如下:

    [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();
    }

推荐答案

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

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

这篇关于如何在没有Authorize属性的ASP Core 2方法中获取用户声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆