User.Identity.IsAuthenticated всегда возвращает false

Я реализую REST API с помощью ASP.NET WEB API 2. У меня есть реализация AccountController по умолчанию с методом для // GET api/Account/ExternalLogin.

[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
    if (error != null)
    {
        return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
    }

    if (!User.Identity.IsAuthenticated)
    {
        return new ChallengeResult(provider, this);
    }

    ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

    if (externalLogin == null)
    {
        return InternalServerError();
    }

    if (externalLogin.LoginProvider != provider)
    {
        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        return new ChallengeResult(provider, this);
    }

    ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
        externalLogin.ProviderKey));

    bool hasRegistered = user != null;

    if (hasRegistered)
    {
        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

         ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
            OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
            CookieAuthenticationDefaults.AuthenticationType);

        AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
        Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
    }
    else
    {
        IEnumerable<Claim> claims = externalLogin.GetClaims();
        ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
        Authentication.SignIn(identity);
    }

    return Ok();
}

Я просмотрел интернет и не нашел ничего подходящего для этой ситуации.

URL я использую

https_://_www.dummydomain.com:43363/ API / счета / ExternalLogin поставщик =Google&response_type= маркер &client_id= &redirect_uri самостоятельно = HTTPS%3A%2F%2Fwww.dummydomain.com%3A43363%2F& состояние =jI4zGXuaVvHI8qf9E0Nww3qBwke0YsYwD9AORwKBj3o1

Каждый внешний сервис (Google/FB) работает корректно. Я вижу, что AspNet.ExternalCookie установлен, но перенаправление назад, я не авторизован и получаю

{
  email:null,
  hasRegistred: true,
  loginProvaider: null
}

Обновление 1

Properties словарь Request собственность на AppController не содержит MS_UserPrincipal,

Смотрите скриншот прилагается. Ключи свойств

Request.Properties["MS_HttpContext"] возвращает: (см. скриншот) MS_HttpContextobject

1 ответ

Невозможно использовать свойство HttpContext непосредственно в APIController. Чтобы получить это, вы должны использовать свойство Request типа System.Net.Http.HttpRequestMessage. HttpRequestMessage имеет словарь свойств; вы найдете значение ключа MS_UserPrincipal, который содержит ваш объект IPrincipal.

Другие вопросы по тегам