首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何启用自定义授权消息

如何启用自定义授权消息
EN

Stack Overflow用户
提问于 2020-06-04 16:21:16
回答 1查看 685关注 0票数 1

免责声明:本主题的结果通常非常陈旧,不一定使用标识核心引用Asp.Net Core3.1。我正试图找到一种现代的推荐解决方案。

我已经使用Identity和JWT创建了一个概念Web应用程序的证明。其想法是导航到网站,并能够登录和查看您的声明,更改您的密码和其他与身份相关的功能。

另一个组件是只对JWT使用Web。

我已经实现了索赔/策略,并且授权运行得很好。总的来说,我对这个概念的证明很满意。

特别是有一件事,还有很多不尽如人意的地方:当用户没有经过身份验证,或者在使用JWT使用API时没有经过身份验证,但没有被授权时,消息就会出现。目前,它所做的就是返回一个403 (已验证但未授权)或401 (未验证)响应代码,没有任何相关消息。

以这个例子为例。我有一个声明,ClaimType: Api, ClaimValue: Delete映射到策略(字符串常量以避免神奇字符串):CanDeletePolicy

代码语言:javascript
运行
复制
options.AddPolicy(Policies.CanDeletePolicy, policy => {
    policy.RequireClaim("Api", "Delete");
});

记住,一切都是按计划进行的。我只是想为API的使用者提供有意义的消息。

财务主任:

代码语言:javascript
运行
复制
[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内的行动:

代码语言:javascript
运行
复制
[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"
    });
}

如果用户试图使用此操作:

  • 但未进行身份验证,它们接收空401响应
  • 被验证,但未授权,它们接收空的403响应

我想提供不同程度的资料:

响应体为“您不是authenticated"

  • 403”和“您没有授权”或“您未被授权: Api,需要更新”的
  • 401,

我有什么选择?创建自定义授权属性?我不想为了增加一个简单的信息而重新发明轮子。我还希望以JSON格式做出授权响应,但我认为这对于建议的解决方案并不重要。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-04 17:09:52

代码语言:javascript
运行
复制
   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; }
}

在创业过程中:

代码语言:javascript
运行
复制
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // put middleware before authentication
        app.UseMiddleware<ResponseFormatterMiddleware>();
        app.UseAuthentication();
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62199488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档