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

问题描述 投票:0回答:1

概述:

我的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);
        }
    }
}
c# asp.net-mvc cookies asp.net-web-api2 asp.net-identity-2
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.