首页 > 解决方案 > MVC 无需重定向即可登录 IdentityServer4

问题描述

所以我试图从我的 ASP.NET Core 2.2 MVC 应用程序登录用户,而不将他们重定向到 IdentityServer4。到目前为止,我能够使用 IS4 的ResourceOwnerPassword流程来获取令牌并使用 获取令牌RequestPasswordTokenAsync,但是即使在我使用访问令牌设置客户端之后,它也没有对我的应用程序进行身份验证。

控制器:

 public async Task<IActionResult> Login()
    {
        var client = new HttpClient();

        var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
        {
            Address = "http://localhost:5000/connect/token",
            ClientId = "mvc3",
            ClientSecret = "secret",
            UserName = "LegitUsername",
            Password = "VeryLegitamitePassword",
            Scope = "api1"
        });

        client.SetBearerToken(response.AccessToken);

        return Redirect("/");
}

当前行为:授予令牌,但我的标题仍然有“登录”按钮

预期行为:授予令牌,显示“注销”按钮

当前的行为表明,即使我持有令牌,我也没有通过身份验证。我知道我缺少一些东西来将令牌传递HttpContext给我的应用程序以验证我的应用程序,但不知道是什么。任何帮助,将不胜感激。

标签: asp.net-mvcjwtidentityserver4dotnet-httpclienthttpcontext

解决方案


好吧,您没有登录用户。您从 id4 请求访问令牌。通常,您请求访问令牌以将其添加到请求(如您所做的那样)以访问资源。

请参考示例:https ://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Clients/src

mvc 有几个示例实现。


推荐阅读