【问题标题】:Wpf app using Web API -Identity Server 4使用 Web API -Identity Server 4 的 Wpf 应用程序
【发布时间】:2018-04-25 13:44:08
【问题描述】:

WPF OidcClient:

var options = new 
    {
    //redirect to identity server
    Authority = "http://localhost:5000/",
    ClientId = "native.code",
    Scope = "openid profile email fiver_auth_api",
    //redirect back to app if auth success
    RedirectUri = "http://127.0.0.1/sample-wpf-app",
    ResponseMode = OidcClientOptions.AuthorizeResponseMode.FormPost, 
    Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
    Browser = new WpfEmbeddedBrowser()
};

WPF 调用 web api:

private void CallButtonAsync()
    {
        var accessToken = token;

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        //on button click call Web api Get movies
        //Initialize HTTP Client 
        client.BaseAddress = new Uri("http://localhost:5001");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        try
        {
            HttpResponseMessage response = client.GetAsync("/movies/get").Result;
            MessageBox.Show(response.Content.ReadAsStringAsync().Result);
        }
        catch (Exception)
        {
            MessageBox.Show("Movies not Found");
        }

    }

身份服务器 - WPF 声明为客户端 //wpf 桌面应用程序

new Client
{
    ClientId = "native.code",
    ClientName = "Native Client (Code with PKCE)",

    RedirectUris = { "http://127.0.0.1/sample-wpf-app" },
    PostLogoutRedirectUris = { "http://localhost:5000" },

    RequireClientSecret = false,
    RequireConsent = true,

    AllowedGrantTypes = GrantTypes.Code,
    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        IdentityServerConstants.StandardScopes.Email,
        IdentityServerConstants.StandardScopes.OfflineAccess,
        "fiver_auth_api"
    },
    AlwaysIncludeUserClaimsInIdToken = true,
    IdentityTokenLifetime=3600,

}

web api 只能在用户授权时使用。我在 wpf 应用程序中获得了令牌,但是在调用 web api 时我得到了 401(未授权)。

我错过了什么?

【问题讨论】:

  • 你考虑过使用IdentityModel Nuget包(DiscoveryClient等)吗?
  • 可能有多种原因。首先检查 IdentityServer 的日志。
  • github.com/IdentityModel/IdentityModel.OidcClient.Samples/tree/… 我开始使用这个 repo。我检查了身份服务器,没关系。我确实在 WPF 应用程序中收到了令牌,但是当我访问 web api 时,我得到了 401。
  • @AlexandraDamaschin 我也有同样的问题,请问您是如何解决的?

标签: wpf asp.net-web-api identityserver4


【解决方案1】:

我最好的是你错过了

AllowOfflineAccess = true

defining the Client at the IdentityServer

【讨论】:

  • 查看您的配置 - 将其与示例匹配 - 您的编辑中有很多不一致之处(例如,在客户端中有 localhost 与 127.0.0.1) - 我链接到的示例代码工作正常.. .
猜你喜欢
  • 2019-09-20
  • 1970-01-01
  • 2020-11-05
  • 2018-02-02
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
相关资源
最近更新 更多