1
votes

I want to make ajax request from MVC site to WebApi using cookie authorization. BUT I've stuck into trouble.

ControllerContext.RequestContext.Principal

is null. It seems it cannot recognize cookies, unless it exists in request. I have two applications 1 - MVC the main 2 - WebApi additional MVC requests WebApi. Both use common Identity Users.

Here is my implementation

  1. Registration for 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. My ApplicationManager is:

    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. The same machineKeys in WebApi and MVC

    <machineKey decryption="AES" decryptionKey="F7F..." validation="SHA1" validationKey="DD2..." />

  4. The controller covered with Authorize attribute

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

Any help please.

1

1 Answers

0
votes

The CORS spec says that if you enable SupportCredentials you are not allowed to set origins to "*". See the paragraph just above the title here.

Does it work if you set origins to something specific?

Also is the request failing when the client hits the /token endpoint or when it hits a real endpoint after authorization has occurred?

If it fails hitting your /token endpoint, then you need to uninstall Microsoft.AspNet.WebApi.Cors and instead install Microsoft.Owin.Cors use that instead.