【问题标题】:Authenticating with MVC application from a Web API authentication通过 Web API 身份验证使用 MVC 应用程序进行身份验证
【发布时间】:2017-03-03 12:23:36
【问题描述】:

概述:

我有一个 Web API 位于 ABC 域 和一个 MVC 应用程序位于 XYZ 域。

当用户使用 API 进行身份验证时,我正在调用 MVC 应用程序,该应用程序复制登录方法并为 MVC 应用程序设置一个 cookie,从而允许用户从一个端点在两个应用程序上进行身份验证。

问题:

从 API 到 MVC 应用程序的调用工作正常,但是没有设置 cookie。因此,当我通过 API 进行身份验证后访问我的 MVC 应用程序时,仍然要求我登录。

对 MVC 应用程序的 Web API 调用:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://xyz.co.uk");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var content = new FormUrlEncodedContent(new[] 
    {
        new KeyValuePair<string, string>("refreshTokenId", token.Id)
    });

    // HTTP POST
    HttpResponseMessage response = await client.PostAsync("Account/LoginFromAPI", content);
}

MVC 应用程序登录(来自 API 调用):

[HttpPost]
[AllowAnonymous]
public void LoginFromAPI(string refreshTokenId)
{
    RefreshToken refreshToken = null;

    // Get refresh token from the API database
    using(var api = new APIContext())
    {
        refreshToken = api.RefreshTokens.SingleOrDefault(x => x.Id == refreshTokenId);
    }

    if (refreshToken != null)
    {
        // Find the user in the MVC application database
        var user = this.UserManager.FindByEmail(refreshToken.Subject);

        if (user !=  null)
        {
            // The below code works fine for normal login through the MVC application, 
            // but not by the call from the API
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            ClaimsIdentity identity = user.GenerateUserIdentity(this.UserManager);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = rememberMe }, identity);
        }
    }
}

【问题讨论】:

    标签: c# asp.net-mvc cookies asp.net-web-api2 asp.net-identity-2


    【解决方案1】:

    问题是您正在为 XYZ 域设置 Cookie。 Cookie 是特定于域的,因此当您向 ABC 域发送请求时,不会附加 cookie,反之亦然。您需要做的是设置一个身份验证服务器,该服务器将为您的应用程序提供单点登录功能。您可以查看 Active Directory Federation Services 或 ThinkTecture IdentityServer。所有请求都将从您的身份验证服务器进行身份验证,并重定向到目标服务器进行处理。这就是 Microsoft 帐户和许多其他帐户管理服务实现单点登录的方式。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-26
      • 2018-03-19
      • 2020-07-24
      • 2016-04-30
      • 2015-09-05
      • 2011-06-27
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多