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

时间:2018-10-12 02:10:07

标签: c# asp.net-core authorization openiddict

我正在学习ASP.NET CORE。我已经成功实现了openiddict来保护我的api。成功登录后,用户会获得一个令牌,该令牌用于访问Web api,但它也允许未经授权的用户(即没有令牌的用户) 这就是我由控制器安排的方式

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

我做错了,请帮帮我。

2 个答案:

答案 0 :(得分:4)

像这样在AuthenticationSchemes属性中设置Authorize

[Authorize(AuthenticationSchemes = 
    OpenIddictValidationDefaults.AuthenticationScheme)]

这将确保授权是通过OAuth令牌而不是Cookies进行的。

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/";
    });

答案 1 :(得分:0)

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

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

在我的ConfigureServices()中进行了误导,试图优化并变得精瘦。好吧,那一定已经优化了一些核心身份验证管道。尽管我的处理程序总是被调用,但是每个请求仍然向控制器发出。

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

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