【问题标题】:Select an endpoint based on User Role根据用户角色选择端点
【发布时间】:2021-11-16 01:22:01
【问题描述】:

是否可以选择基于 Web API 中的用户角色的端点? 我想在一个控制器中为不同角色提供几种方法,但找不到合适的解决方案。

编辑: 我有一个具有基于角色的授权的典型 UserController。我想在控制器中有两种方法,例如。 SearchForAdmin 和 SearchForUser(都带有 URL ../users/search)。该方法应根据 B2C 令牌中的角色进行选择。关于如何实现这一目标的任何想法?

【问题讨论】:

  • 你能否分享一些代码,即使它不起作用,你想要完成什么?你现在的问题有点含糊,所以不确定解决方案的方向。
  • @BenMatthews 我已经更新了问题,也许现在更具描述性。我没有开始实施它,因为我首先在寻找可能的解决方案。

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


【解决方案1】:

端点的 RequireAuthorization 函数可能是您正在寻找的。我没有尝试使用具有相同路径的两个不同端点进行此操作,唯一的区别是两个不同的策略,但我知道具有不同要求主机的两条路径将起作用。例如,我知道这对我有用:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapGet("/Foo", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                }).RequireHost("Something.com");


                endpoints.MapGet("/Foo", async context =>
                {
                    await context.Response.WriteAsync("Hello World From Local!");
                }).RequireHost("localhost");
            });

我认为如果你尝试这个,如果它保持一致,它应该可以工作:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapGet("/Foo", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                }).RequireAuthorization("FirstAuthPolicy", "SecondAuthPolicy");


                endpoints.MapGet("/Foo", async context =>
                {
                    await context.Response.WriteAsync("Hello World from a second place!");
                }).RequireAuthorization("ThirdAuthPolicy");
            });

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 2017-06-01
    • 2019-06-16
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多