在ASP.NET MVC项目和Web API项目之间共享cookie

Gio*_*zas 7 asp.net-mvc authorization asp.net-web-api

我有一个有2个项目的解决方案.一个是ASP.NET MVC Web应用程序,另一个是Web API项目.我想要做的是在两个应用程序之间共享cookie.在服务器上部署时,第一个应用程序托管在mydomain.com上,另一个应用程序托管在api.mydomain.com(子域)上.我也使用https.我在MVC项目中使用ASP.NET Identity作为身份验证系统.在互联网上阅读了大量文章后,我做了以下工作:

1)在web.config文件中,在两个项目中都包含以下机器密钥标记.

<machineKey validationKey="3DF5D185FFB897592E14ED51A6DDC3E2729827A2F2180151A1BC39BE5C035D15F23700C928EFDBACEAEE498D05B76C65537FDEFB673039BCD961045C3BA8ACD3" 
            decryptionKey="CE274BA1DB61C086A80F5D8BD1AC5AC92A8BA19F37E04FC7" validation="SHA1" />
Run Code Online (Sandbox Code Playgroud)

2)在MVC项目中,我以下列方式配置了ASP.NET Identity Cookie:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Home/index"),
      Provider = new CookieAuthenticationProvider
      {  
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(TimeSpan.FromMinutes(30), (manager, user) => user.GenerateUserIdentityAsync(manager))
      },
      SlidingExpiration = true,
      ExpireTimeSpan = TimeSpan.FromMinutes(45),
      CookieName = "MyCookie",
      CookieDomain = ".mydomain.com"
 });
Run Code Online (Sandbox Code Playgroud)

3)在Web API项目中,我启用并配置了CORS,我在web.config中添加了以下配置(CORS在生产环境中正常工作):

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Credentials" value="true"></add>
    <add name="Access-Control-Allow-Origin" value="mydomain.com" />
    <add name="Access-Control-Allow-Headers" value="content-type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)

4)我已经添加了httpCookies部分(在两个项目中),如下所示:

<httpCookies requireSSL="true" domain=".mydomain.com" httpOnlyCookies="true" />
Run Code Online (Sandbox Code Playgroud)

在我的Web API控制器中,我已应用Authorize属性,如下所示:

[Authorize]
public class MyController : ApiController
{
   //My action methods here
}
Run Code Online (Sandbox Code Playgroud)

最后,我从MVC项目尝试使用jQuery Ajax请求调用我的服务.

$.ajax({
   url: viewModelParameters.myUrl,
   type: "get",
   dataType: "json",
   data: { userId: viewModelParameters.id },
   xhrFields: {
      withCredentials: true
   },
   crossDomain: true,
   statusCode: {
      200: function (user) {
      }
   }
});
Run Code Online (Sandbox Code Playgroud)

我收到以下消息:

此请求已被拒绝授权.

在请求标头中,我可以看到cookie包含在请求中.你能否提出解决方案或者想一想我错过了什么?先感谢您.

sol*_*dau 0

您需要将其包含app.UseCookieAuthentication()在 WebAPI 和 MVC 项目中。