跨域cookie身份验证麻烦WebApi ASP.NET

时间:2016-07-26 15:21:32

标签: asp.net asp.net-mvc asp.net-web-api cors asp.net-identity

我想使用cookie授权从MVC站点向WebApi发出ajax请求。 但 我遇到了麻烦。

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中的同一台机器

    &lt; machineKey decryption =“AES”decryptionKey =“F7F ......” validation =“SHA1”validationKey =“DD2 ...”/&gt;

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

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

1 个答案:

答案 0 :(得分:0)

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

如果将origins设置为特定内容,是否有效?

当客户端命中/token端点或在授权发生后命中真实端点时,请求是否失败?

如果无法点击/token端点,则需要卸载Microsoft.AspNet.WebApi.Cors,而是安装Microsoft.Owin.Cors使用该端点。