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

本文关键字:身份验证 应用程序 MVC Web API 通过 | 更新日期: 2023-09-27 18:14:05

概述:

我有一个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);
        }
    }
}

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

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