【问题标题】:How to Access MVC API which is authorize with IdentityServer4如何访问通过 IdentityServer4 授权的 MVC API
【发布时间】:2019-03-20 04:47:20
【问题描述】:

在 Owin 中间件启动类中,我添加了 OIDC 身份验证,其中响应类型为“code id_token”。有了这个中间件,我可以访问我的授权控制器。但问题是,我无法使用此中间件访问同一域中的 API。

我正在使用我存储在 userClaim 中的 access_token。但它正在返回 IdentityServer4 登录页面的 HTML。

    [Filters.AuthorizeOIDC(Roles = "dukkan.sa")]
    public async Task<ActionResult> ViewApiResult()
    {
        var user = User as System.Security.Claims.ClaimsPrincipal;
        var token = user.FindFirst("access_token").Value;
        var result = await CallApi(token);

        ViewBag.Json = result;
        return View();
    }

    private async Task<string> CallApi(string token)
    {
        var client = new HttpClient();
        client.SetBearerToken(token);

        var json = await client.GetStringAsync("http://localhost:57346/api/SampleApi");
        return json;
    }

我获得的保护 MVC API 的示例是使用 IdentityServer3。他们在 API 访问请求期间使用 IdentityServer3.AccessTokenValidation 包从后台通道对客户端进行身份验证:

app.UseOAuthBearerAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority = "https://localhost:44319/identity", RequiredScopes = new[] { "sampleApi" } });

但 IdentityServer4.AccessTokenValidation 不适用于 MVC5。我可以在 MVC 5 中使用 IdentityServer3.AccessTokenValidation。但这是接受低于 2.0.0 版本的 IdentityModel。

需要解决方案。 IdentityServer4 没有正确支持 MVC。

【问题讨论】:

  • 曾经成功过吗?
  • 嗨,@RuardvanElburg,目前我已将我的 MVC webAPI2 转换为 .net Core 2 以使用 IdentityServer4 对其进行身份验证。稍后,我将通过在 .net 4.5 中制作我的完整项目而不是当前的 .net v4.6.2 来再次尝试。

标签: authentication asp.net-mvc-5 access-token identityserver4 openid-connect


【解决方案1】:

为什么要在 MVC5 中使用 IdentityServer4.AccessTokenValidation?因为服务器是IdentityServer4?

没有必要这样做。 IdentityServer3 和 IdentityServer4 建立在相同的 OpenId Connect 规范上,这意味着您可以将 IdentityServer3.AccessTokenValidation 用于客户端,而服务器是 IdentityServer4。

事实上,您可以在客户端上使用根据 OpenId Connect 规范构建的任何代码。我建议你试试 IdentityServer3.AccessTokenValidation。

【讨论】:

  • 亲爱的 Ruard,感谢您的回复。我尝试使用 IdentityServer3.AccessTokenValidation。但我与 IdentityModel 版本发生冲突。我当前的 IdentityModel 超过 4.0,但 IdentityServer3.AccessTokenValidation 只接受 v.1 和下面的 v.2。我试图通过降低我的最新版本来实现它。但是版本冲突使解决方案变得困难。
  • 我不明白你的版本是4,你确定是同一个包吗?因为IdentityModel的最新版本是3.10。您可能希望删除已安装的所有包并开始安装 IdentityServer3.AccessTokenValidation 包。这应该包括正确的包,包括 IdentityModel 1.13.1。然后添加缺少的包。这是否解决了冲突的版本?
  • 以下是我用于 .net 4.5 项目的一些包:
  • 我按照你写的修改了版本。我收到此错误"Could not load file or assembly 'Microsoft.IdentityModel.Logging' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)" 说真的,他们需要更新 IdentityServer3.AccessTokenValidation。另一件事,您是否使用ResponseType = OpenIdConnectResponseTypes.IdToken 进行API 资源访问?您如何获得访问令牌?你能分享你的代码吗?
  • 也许您需要旧版本。这可能取决于 .net 框架版本。这里有很多样例:github.com/IdentityServer/IdentityServer3.Samples/tree/master/…
猜你喜欢
  • 2020-02-17
  • 1970-01-01
  • 2015-08-13
  • 2012-11-19
  • 2020-12-26
  • 2018-12-11
  • 2012-11-16
  • 2020-03-23
  • 2019-04-19
相关资源
最近更新 更多