【问题标题】:Owin not authenticated when requesting access token请求访问令牌时 Owin 未通过身份验证
【发布时间】:2020-06-26 12:56:34
【问题描述】:

我正在使用隐式授权类型,当我请求“id_token token”作为响应类型时,我的 HttpContext.Current.User 在登录后为空,导致我相信 owin 内部出现问题。如果我只有“id_token”作为响应类型,那很好。我需要告诉 owin 在某个地方获取访问令牌吗?

作为参考,我使用 .Net Framework 作为我的客户端和 identityserver4。

【问题讨论】:

    标签: owin identityserver4


    【解决方案1】:

    为了能够通过浏览器获取令牌,您需要在 IdentityServer 中的客户端配置中设置 AllowAccessTokensViaBrowser = true

                    new Client
                    {
                        ...
    
                        AllowedGrantTypes = GrantTypes.Implicit,
                        AllowAccessTokensViaBrowser = true,
    
                        ...
                    },
    

    在 MVC 客户端的启动中,您可以将 access_token 添加为对用户的声明:

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    ...
                    ResponseType = "id_token token",             
    
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = n =>
                        {
                            n.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
                            
                            return Task.FromResult(0);
                        }
                    }
                });
    

    我有完整的工作示例here

    【讨论】:

    • 太棒了,谢谢!作为后续,我将如何使用此访问令牌与身份服务器中的本地 API 通信?
    • 调用api时获取access_token并设置在request header中即可。这是一个例子github.com/nahidf-adventures/IdentityServer4-adventures/blob/…。唯一的区别是,在您的情况下,您从用户的声明中获得了 access_token。 IDS4 中的本地 API 与任何其他 API 一样
    • 没关系 - 想通了。如果其他人想知道这对我有用: HttpClient client = new HttpClient(); client.BaseAddress = new Uri("localhost:5000/api/Users/TestMethod"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenHelper.GetAccessToken()); 然后继续执行通常的http请求。仅供参考,tokenHelper 只是让我得到值access_token 声明。再次感谢 nahidf 的帮助!
    • @Josh np,很高兴能帮上忙,请随时阅读我的​​博客nahidfa.com/posts/identityserver4-and-asp-.net-mvc/…
    猜你喜欢
    • 2019-10-19
    • 2018-08-27
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多