2016-07-26 58 views
1

我想使用cookie授权从MVC网站向WebApi发送ajax请求。 但是 我陷入困境。跨域cookie认证麻烦WebApi ASP.NET

ControllerContext.RequestContext.Principal 

为空。它似乎无法识别Cookie,除非它存在于请求中。 我有两个应用程序 1 - MVC主要 2 - WebApi额外 MVC请求WebApi。两者都使用普通的身份用户

这是我实现

  1. 登记IAppBuilder

    public static void Register(IAppBuilder app) 
        { 
         app.CreatePerOwinContext(MyDbContext.Create); 
         app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
         app.UseCookieAuthentication(new CookieAuthenticationOptions() 
         { 
          AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
          CookieName = ".AspNet.Cookies", 
          CookieSecure = CookieSecureOption.Never, 
          AuthenticationMode = AuthenticationMode.Active 
         }); 
    
         app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 
        } 
    
  2. 我ApplicationManager是:

    public class ApplicationUserManager : UserManager<ApplicationUser> { 
    public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) 
    { 
    } 
    
    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    { 
        var appDbContext = context.Get<MyDbContext>(); 
        var appUserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(appDbContext)); 
        return appUserManager; 
    } } 
    
  3. 中的WebAPI和MVC

    同样MachineKeys的

    <的machineKey解密= “AES” decryptionKey = “F7F ...” 验证= “SHA1” 的validationKey = “DD2 ...”/ >

  4. 覆盖有授权控制器属性

    [Authorize] 
    [EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)] 
    public sealed class BalanceController : ApiController ... 
    

请任何帮助。

回答

0

CORS规范说,如果启用SupportCredentials,则不允许将origins设置为"*"。请参阅标题here上方的段落。

如果您将origins设置为特定的内容,它会起作用吗?

当客户端遇到/token端点时,或者在授权发生后它碰到真正的端点时,请求失败吗?

如果未能击中/token端点,则需要卸载Microsoft.AspNet.WebApi.Cors,而改为使用Microsoft.Owin.Cors替代。