免责声明:本主题的结果通常非常陈旧,不一定使用标识核心引用Asp.Net Core3.1。我正试图找到一种现代的推荐解决方案。
我已经使用Identity和JWT创建了一个概念Web应用程序的证明。其想法是导航到网站,并能够登录和查看您的声明,更改您的密码和其他与身份相关的功能。
另一个组件是只对JWT使用Web。
我已经实现了索赔/策略,并且授权运行得很好。总的来说,我对这个概念的证明很满意。
特别是有一件事,还有很多不尽如人意的地方:当用户没有经过身份验证,或者在使用JWT使用API时没有经过身份验证,但没有被授权时,消息就会出现。目前,它所做的就是返回一个403 (已验证但未授权)或401 (未验证)响应代码,没有任何相关消息。
以这个例子为例。我有一个声明,ClaimType: Api, ClaimValue: Delete
映射到策略(字符串常量以避免神奇字符串):CanDeletePolicy
options.AddPolicy(Policies.CanDeletePolicy, policy => {
policy.RequireClaim("Api", "Delete");
});
记住,一切都是按计划进行的。我只是想为API的使用者提供有意义的消息。
财务主任:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class PeopleController : ControllerBase {
private readonly ILogger<PeopleController> _logger;
private readonly IPeopleService _peopleService;
public PeopleController(ILogger<PeopleController> logger, IPeopleService peopleService) {
_logger = logger;
_peopleService = peopleService;
}
...
PeopleController内的行动:
[HttpDelete("[action]/{id:int}")]
[Authorize(Policy = Policies.CanDeletePolicy)]
public IActionResult Delete(int id) {
var result = _peopleService.Delete(id);
var username = User.FindFirstValue(ClaimTypes.Name);
if (result < 1) {
var message = $"User '{username}' was unable to delete a person with Id {id}";
_logger.LogError(message);
return BadRequest(new {
Message = message
});
}
var successMessage = $"User '{username}' successfully deleted the person with Id {id}";
_logger.LogDebug(successMessage);
return Ok(new {
Message = "Person deleted"
});
}
如果用户试图使用此操作:
。
我想提供不同程度的资料:
响应体为“您不是authenticated"
我有什么选择?创建自定义授权属性?我不想为了增加一个简单的信息而重新发明轮子。我还希望以JSON格式做出授权响应,但我认为这对于建议的解决方案并不重要。
发布于 2020-06-04 17:09:52
public class ResponseFormatterMiddleware
{
private readonly RequestDelegate _next;
public ResponseFormatterMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
{
await context.Response.WriteAsync(
JsonConvert.SerializeObject(new ResponseModel("some-message")));
}
}
}
public class ResponseModel
{
public ResponseModel(string message)
{
this.Message = message;
}
public string Message { get; set; }
}
在创业过程中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// put middleware before authentication
app.UseMiddleware<ResponseFormatterMiddleware>();
app.UseAuthentication();
}
https://stackoverflow.com/questions/62199488
复制相似问题