ASP.NET CORE 2.0 - [授权] 不阻止其余 api 未经授权的用户访问

ASP.NET CORE 2.0 - [Authorize] doen't block the rest api access to unauthorized user

我正在学习 ASP.NET 核心课程。我已经成功实施 openiddict 来保护我的 api。成功登录后,用户获得一个令牌,该令牌用于访问网络 api 但它也允许未经授权的用户(即没有令牌的用户) 我是这样安排的 controller

namespace ISIA.Controllers
{
  [Authorize]
  [Route("api/[controller]")]
  public class PostController: Controller
  {
    private readonly IPostService _postService;
    private readonly PostToPostViewModelMapper _mapper;
    public PostController(
      IPostService postService
      )
    {
      _postService = postService;
      _mapper = new PostToPostViewModelMapper();
    }


    [HttpPost]
    public ObjectResult SavePost([FromBody] PostViewModel postViewModel)
    {
                 //method body
    }

    [HttpGet]
    public ObjectResult GetAllPost()
    {
       //method body  
    }
  }
}

在状态中

 services.AddOpenIddict(options =>
      {
        options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
        options.AddMvcBinders();
        options.EnableAuthorizationEndpoint("/connect/authorize")
                       .EnableLogoutEndpoint("/connect/logout")
                       .EnableTokenEndpoint("/connect/token")
                       .EnableUserinfoEndpoint("/api/userinfo");
        options.AllowAuthorizationCodeFlow();
        options.RequireClientIdentification();
        options.AllowPasswordFlow();
        options.AllowRefreshTokenFlow();
        options.DisableHttpsRequirement();
        options.UseRollingTokens(); //Uncomment to renew refresh tokens on every refreshToken request
                                    // options.AddSigningKey(new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["STSKey"])));
        options.Configure(
          config =>
          {
            // Enable sliding expiration
            config.UseSlidingExpiration = true;
            config.AccessTokenLifetime = TimeSpan.FromMinutes(240);
            config.RefreshTokenLifetime = TimeSpan.FromDays(15);
          });
      });

我做错了什么请帮助我。

像这样在 Authorize 属性中设置 AuthenticationSchemes

[Authorize(AuthenticationSchemes = 
    OpenIddictValidationDefaults.AuthenticationScheme)]

这将确保使用 OAuth 令牌而不是 Cookie 完成授权。

OpenIddictValidationDefaults.AuthenticationScheme is defined here.

使用特定方案授权 is documented here

如果失败,正如您的评论所暗示的那样,那么您需要configure a token handler。看起来像这样:

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => 
    {
        options.Audience = "https://localhost:5001/";
        options.Authority = "http://localhost:5000/";
    });

就我而言,我愚蠢地试图变得圆滑,只用

滚动
services.AddMvcCore()
    .AddFormatterMappings()
    .AddJsonFormatters()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

在我的 ConfigureServices() 中错误地尝试优化和精简。好吧,这一定已经优化了一些核心身份验证管道。虽然我的处理程序总是被调用,但每个请求仍然会到达控制器。

通过添加到核心管道解决:

services.AddMvcCore()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .AddFormatterMappings()
    .AddJsonFormatters()
    .AddAuthorization();