从 Web API 身份验证使用 MVC 应用程序进行身份验证

Authenticating with MVC application from a Web API authentication

概览:

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

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

问题:

从 API 到 MVC 应用程序的调用工作正常,但是未设置 cookie。因此,在使用 API.

进行身份验证后访问我的 MVC 应用程序时仍然要求我登录

Web API 调用 MVC 应用程序:

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);
        }
    }
}

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