【问题标题】:IdentityServer 4 with MVC 5 .Net Framework client that already uses ASP.Net Identity FrameworkIdentityServer 4 和 MVC 5 .Net Framework 客户端已经使用了 ASP.Net Identity Framework
【发布时间】:2019-01-21 01:24:00
【问题描述】:

我有一个旧的 ASP.Net MVC 5 应用程序,它已经实现了身份框架以将用户登录到网站。我们已经开始转向微服务架构,现在需要对向 api 发出的请求进行身份验证(api 位于 .net 核心中)。

我已经成功地创建了一个身份服务器,并使用邮递员和 ResourceOwnerPasswordAndClientCredentials 流程创建了 jwt 令牌,并在 API 上对用户进行身份验证,同时还可以提取声明。

mvc 应用程序有一个类似于 airbnb 的登录页面(登录表单是主页上的弹出窗口),因此将网站重定向到身份服务器并不是一个真正的选择。

问题是我应该使用什么流程?

我的客户端在身份服务器中目前如下所示:

new Client
{
    ClientId = "ClientWebsite",
    ClientSecrets = new[] { new Secret("secret".Sha256()) },
    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
    AllowedScopes = new[] {
        "WebsiteAPI",
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        IdentityServerConstants.StandardScopes.Email
    }
},

正如提到的在客户端网站已经设置为使用 Cookie Authentication 进行身份验证,启动看起来像这样:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString(Settings.FormsAuthPath),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

我知道我需要在此之后添加一些内容。任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-identity identityserver4 identityserver3


    【解决方案1】:

    由于您的目标是完全控制登录页面,我肯定会说您在 ResourceOwnerPassword 流程的正确路径上。我不确定您为什么还要包含客户端凭据授权类型,但您指定的用户身份验证方式不需要它。

    根据您迄今为止构建的内容,我建议确保资源所有者密码流程所需的一切都已实现。此流程需要做的主要事情是实现指定here 的IResourceOwnerPasswordValidator 接口。之后,您应该可以直接向token endpoint 'connect/token' 发出请求。只要您在表单帖子中指定了所有正确的字段(如spec 中所述的grant_type、用户名、密码和范围),您就应该毫无问题地获得您的访问权限和 id 令牌!

    【讨论】:

    • 感谢 Randy 的回复,从身份服务器方面对我来说这很有意义。我对来自客户端网站方面的流程有点困惑。登录后,我是否会使用诸如 HttpClient 之类的东西向身份服务器发出手动 http 请求以获取令牌,如果是这样,我如何确保将令牌传递到 http 上下文中?
    • 向 IdentityServer 的令牌端点发出请求后,您应该在响应中收到身份(和访问)令牌。所以是的,要发出该令牌请求,您可以使用客户端 HttpClient。要将身份令牌的信息持久保存到客户端的 HttpContext 中,我将从令牌声明创建一个 ClaimsPrincipal 并使用 ASP.NET Core 的“SignInAsync”(这是 HttpContext 上的扩展方法)来设置客户端的 cookie登录响应。这样,在下一个请求中,您应该能够从 HttpContext 访问“用户”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2018-09-13
    • 1970-01-01
    • 2018-06-27
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多