gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:56:48 24 4
gpt4 key购买 nike

我正在学习 ASP.NET CORE。我已成功实现 openiddict 来保护我的 api。成功登录后,用户获得一个 token ,该 token 用于访问 web api,但它也允许未经授权的用户(即没有 token 的用户)这是我通过 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 token 而不是 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/";
});

关于c# - ASP.NET CORE 2.0 - [授权] 不阻止对未授权用户的其余 api 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com