2015-11-28 1 views
1

У меня есть настройки проекта в Google, и он дал мне AppID и секретный enter image description hereASP.Net Идентичность и Google Authentication Выпуск

Я переместил идентификатор и секрет StartUp.Auth

public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 

      app.CreatePerOwinContext<IdentityTestingDbContext>(IdentityTestingDbContext.Create); 
      app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
      app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

      app.UseCookieAuthentication(new CookieAuthenticationOptions 
      { 
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
       LoginPath = new PathString("/Account/Login"), 
      }); 

      app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 


      app.UseGoogleAuthentication(
       clientId: "*********************.apps.googleusercontent.com ", 
       clientSecret: "**************"); 


     } 
    } 

Здесь являются действиями для внешнего входа в систему, я следую за Приложением Identity Sample (пакет установки Microsoft.AspNet.Identity.Samples -Pre).

[HttpPost] 
     [AllowAnonymous] 
     [ValidateAntiForgeryToken] 
     public ActionResult ExternalLogin(string provider, string returnUrl) 
     { 
      // Request a redirect to the external login provider 
      var challenge = new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); 
      return challenge; 
     } 
     // Used for XSRF protection when adding external logins 
     private const string XsrfKey = "XsrfId"; 
     internal class ChallengeResult : HttpUnauthorizedResult 
     { 
      public ChallengeResult(string provider, string redirectUri) 
       : this(provider, redirectUri, null) 
      { 
      } 

      public ChallengeResult(string provider, string redirectUri, string userId) 
      { 
       LoginProvider = provider; 
       RedirectUri = redirectUri; 
       UserId = userId; 
      } 

      public string LoginProvider { get; set; } 
      public string RedirectUri { get; set; } 
      public string UserId { get; set; } 

      public override void ExecuteResult(ControllerContext context) 
      { 
       var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; 
       if (UserId != null) 
       { 
        properties.Dictionary[XsrfKey] = UserId; 
       } 
       context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); 
      } 
     } 

     [AllowAnonymous] 
     public async Task<ActionResult> ExternalLoginCallback(string returnUrl) 
     { 
      var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 
      if (loginInfo == null) 
      { 
       return RedirectToAction("Login"); 
      } 

      var user = await UserManager.FindAsync(loginInfo.Login); 
      if (user == null) 
      { 
       user = new ApplicationUser 
       { 
        Email = loginInfo.Email, 
        UserName = loginInfo.DefaultUserName, 
        FirstName = string.Empty, 
        LastName = string.Empty 
       }; 

       var result = await UserManager.CreateAsync(user); 
       if (!result.Succeeded) 
       { 
        return View("Error", result.Errors); 
       } 

       result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); 
       if (!result.Succeeded) 
       { 
        return View("Error", result.Errors); 
       } 
      } 

      var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); 
      identity.AddClaims(loginInfo.ExternalIdentity.Claims); 
      AuthenticationManager.SignIn(new AuthenticationProperties 
      { 
       IsPersistent = false 
      }, identity); 
      return Redirect(returnUrl ?? "/"); 
     } 

Я перенаправляюсь в Google, но здесь я получаю сообщение об ошибке. Похоже, я что-то упускаю, но не могу понять. Я искал почти 3 часа и не мог найти ничего, чтобы помочь с этой проблемой.

  1. Вы видите что-нибудь, что я могу делать неправильно?
  2. Почему перенаправить URL на изображении ниже http://localhost:58286/signin-google

enter image description here

ответ

3

Вслед помогли

http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on

Fix 1: нуждается Уставной Перенаправление URL быть http://localhost:58286/signin-google, для Google установите экранный снимок в указанной теме. Это не метод обратного вызова внутри контроллера учетных записей.

Fix 2: Мне также нужно было включить API Google+, который я не использовал при настройке

 Смежные вопросы

  • Нет связанных вопросов^_^