【问题标题】:MVC Role Authorization via OpenId from IdentityServer 4通过来自 IdentityServer 4 的 OpenId 进行 MVC 角色授权
【发布时间】:2020-10-08 08:42:56
【问题描述】:

我正在尝试学习身份服务器 4,除了我的 MVC 客户端中的角色授权之外,我的所有功能都在工作(它通过从我的 MVC 客户端调用的 JWT Bearer 在我的 Web API 中正常工作)。

几个小时以来,我一直在寻找并尝试实施潜在的修复,但我似乎没有取得任何进展,所以我认为我错过了这个难题的一个小而关键的部分。

这是我的 MVC 客户端 StartUp 的(部分):

.AddOpenIdConnect("oidc", options =>
{
    options.Authority = appSettings.IdentityUrl;
    options.RequireHttpsMetadata = false;

    options.ClientId = "mvc";
    options.ClientSecret = "secret";
    options.ResponseType = "code id_token";

    options.SaveTokens = true;

    options.Scope.Add("web_api");
    options.Scope.Add("offline_access");

    // I was under the impression that was the 'magic' part which mapped claims to roles for use with the Authorize() attribute
    options.ClaimActions.MapJsonKey("role", "role", "role");
}

这是我登录后获得的 access_token 的有效负载,如您所见,角色在那里:

{
    "nbf": 1592473463,
    "exp": 1592477063,
    "iss": "https://localhost:5000",
    "aud": "web_api",
    "client_id": "mvc",
    "sub": "b2657e83-4256-4fe2-86e9-3bfa53d462e2",
    "auth_time": 1592473458,
    "idp": "local",
    "is_enabled": "True",
    "role": [
        "Player",
        "Admin"
    ],
    "scope": [
        "openid",
        "profile",
        "web_api",
        "offline_access"
    ],
    "amr": [
    "pwd"
    ]
}

返回拒绝访问的示例 MVC 控制器端点:

[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> AuthorisedOnly()
{
    ...SNIP...

    return View("Access", vm);
}

我假设(可能是错误的)如果我的 access_token 中有角色,那么我的身份数据库和ProfileService 设置正确。 (我在ProfileServiceGetProfileDataAsync 中添加角色)。

欢迎提出任何建议,如果您需要有关我的设置的更多信息,请告诉我。我不想用大量不相关的配置数据来夸大这个问题。

【问题讨论】:

标签: asp.net-mvc asp.net-core identityserver4 openid-connect


【解决方案1】:

感谢他的评论中提到的article@RuardvanElburg,我找到了答案。与其说是文章本身,不如说是处理TokenValidationParamters 的代码的sn-p,其中提到了我看到并认为可能会起作用的“角色”。文章中的 cmets 也对我有帮助,远远超过主要文章,但这与 Identity Server 官方文章/文档的课程相当!

options.GetClaimsFromUserInfoEndpoint = true;
options.TokenValidationParameters = new TokenValidationParameters
{
    NameClaimType = "name",
    RoleClaimType = "role"
};

//options.ClaimActions.MapJsonKey("role", "role", "role");
options.ClaimActions.MapUniqueJsonKey("role", "role");

【讨论】:

    猜你喜欢
    • 2014-01-23
    • 2014-05-08
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多