solucionar solucion solicitud servidor recurso que página puede procesar problema mostrar interno hay gramblr funciona esta error elempleo con como busca ahora asp.net-mvc-4 asp.net-mvc-5 katana

asp.net mvc 4 - solucion - Problema con GoogleOauth2 Error interno del servidor 500



phpmyadmin error 500 (5)

Decidí probar el nuevo middleware de Google Oauth2 y prácticamente ha roto todo. Aquí está la configuración de mi proveedor de startup.auth.cs. Cuando está activada, todos los proveedores, incluido el proveedor de Google, obtienen un servidor interno 500 en Challenge. Sin embargo, los detalles del error interno del servidor no están disponibles y no puedo averiguar cómo activar cualquier depuración o seguimiento del middleware Katana. Me parece que estaban apurados por sacar el middleware Oauth de Google por la puerta.

//// GOOGLE var googleOptions = new GoogleOAuth2AuthenticationOptions { ClientId = "228", ClientSecret = "k", CallbackPath = new PathString("/users/epsignin") SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie, Provider = new GoogleOAuth2AuthenticationProvider { OnAuthenticated = context => { foreach (var x in context.User) { string claimType = string.Format("urn:google:{0}", x.Key); string claimValue = x.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) context.Identity.AddClaim(new Claim(claimType, claimValue, XmlSchemaString, "Google")); } return Task.FromResult(0); } } }; app.UseGoogleAuthentication(googleOptions);

Código ActionMethod:

[AllowAnonymous] public ActionResult ExternalProviderSignIn(string provider, string returnUrl) { var ctx = Request.GetOwinContext(); ctx.Authentication.Challenge( new AuthenticationProperties { RedirectUri = Url.Action("EPSignIn", new { provider }) }, provider); return new HttpUnauthorizedResult(); }


Consiguió que funcionara a la perfección en el tutorial con UN simple cambio: solo publique esto para cualquier enfoque de este enfoque. Creo que los problemas relacionados con oauth2 en este caso están muy desarrollados en las últimas plantillas / apis. Lo que quiero decir es que, si estás empezando desde cero, puedes tener suerte. Sigue leyendo:

Acabo de hacer este tutorial https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/

e hizo referencia a esto también http://blogs.msdn.com/b/webdev/archive/2014/07/02/changes-to-google-oauth-2-0-and-updates-in-google-middleware-for-3-0-0-rc-release.aspx

El único cambio: funcionó, pero SOLO después de habilitar las apis de google + en la versión más reciente del sitio para desarrolladores de google.

(Solo vaya al administrador de Google Api Lib, inicie sesión y busque el directorio de apis para google + api).
Nota: para mí, la API de Google+ estaba deshabilitada por defecto.

No hice nada más único.

Aclamaciones


Esto me tomó horas para averiguarlo, pero el problema es el CallbackPath como lo menciona @CrazyCoder. Me di cuenta de que el CallbackPath en public void ConfigureAuth(IAppBuilder app) DEBE ser diferente a cuando se establece en el ChallengeResult . Si son iguales, se lanza un error 500 en OWIN.

Mi código es para ConfigureAuth(IAppBuilder app) es

var googleOptions = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions { ClientId = "xxx", ClientSecret = "yyy", CallbackPath = new PathString("/callbacks/google"), //this is never called by MVC, but needs to be registered at your oAuth provider Provider = new GoogleOAuth2AuthenticationProvider { OnAuthenticated = (context) => { context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString())); context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString())); return Task.FromResult(0); } } }; googleOptions.Scope.Add("email"); app.UseGoogleAuthentication(googleOptions);

El código de mi controlador de ''devoluciones de llamada'' es:

// GET: /callbacks/googlereturn - callback Action [AllowAnonymous] public async Task<ActionResult> googlereturn() { return View(); } //POST: /Account/GooglePlus public ActionResult GooglePlus() { return new ChallengeResult("Google", Request.Url.GetLeftPart(UriPartial.Authority) + "/callbacks/googlereturn", null); //Needs to be a path to an Action that will handle the oAuth Provider callback } private 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); } }

  • Callbacks / google parece manejado por OWIN
  • Las devoluciones de llamada / googlereturn parecen ser manejadas por MVC

Todo está funcionando ahora, aunque me encantaría saber exactamente qué está sucediendo ''bajo el capó''.

Mi consejo, a menos que tenga otro requisito, es dejar que OWIN use las rutas de redirección predeterminadas y asegurarse de que no las use usted mismo.


Estoy usando la plantilla predeterminada de ASP.NET MVC 5 con autenticación de identidad para simplificar, pero espero que esto pueda modificarse para diferentes casos de uso.

StartupAuth.cs

No personalice la ruta de redirección. Se reemplaza por / signin-google de todos modos y mis intentos de solucionar eso causaron errores "silenciosos" (no en el depurador) Internal Server 500.

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = "whatevs.apps.googleusercontent.com", ClientSecret = "whatevs_secrut", Provider = new GoogleOAuth2AuthenticationProvider() });

Asegúrese de agregar http://whatever.com/signin-google a https://console.developers.google.com/ en sus APIs & auth > Credentials > Redirect URIs sección de Redirect URIs .

RouteConfig.cs

Agregue una ruta a una acción de controlador de redireccionamiento permanente a sus rutas. Las redirecciones permanentes son lo único que bastará aquí. No es suficiente simplemente dirigir directamente a la URL de devolución de llamada.

public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Google API Sign-in", url: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallbackRedirect" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }

AccountController.cs

Redirección permanente al método de devolución de llamada incorporado y debería estar bien.

[AllowAnonymous] public ActionResult ExternalLoginCallbackRedirect(string returnUrl) { return RedirectPermanent("/Account/ExternalLoginCallback"); }

Se ha publicado un proyecto de plantilla en GitHub para referencia: https://github.com/Pritchard/Test-AspNetGoogleOAuth2Authentication


Las respuestas dadas hasta ahora me llevaron por un camino muy oscuro que desearía no haber viajado ... la solución es simple, asegúrese de que las siguientes 3 cosas coincidan:

1) En las credenciales de OATH de Google ( https://console.developers.google.com/ ):

2) En su AccountController :

[HttpPost] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); }

Observe que la acción es "ExternalLoginCallback"

3) En tu App_Start/Startup.Auth.cs

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = "yourclientid.apps.googleusercontent.com", ClientSecret = "yoursecret", Provider = new GoogleOAuth2AuthenticationProvider(), CallbackPath = new PathString("/Account/ExternalLoginCallback") });

Observe que el CallbackPath nuevamente tiene el mismo PathString que los otros 2

Finalmente, si aún no lo está obteniendo, configure su modo de autenticación en Ninguno en su aplicación Web.config

<authentication mode="None" />

para obtener más detalles sobre el tema.


No es necesario especificar CallbackPath en UseGoogleAuthentication :

CallbackPath = new PathString("/Account/ExternalLoginCallback")

Solo mantenga la configuración de Google para URIs redireccionamiento autorizado como:

http (s): // yoururl: orPort / signin -google

Owin maneja signin-google internamente y redirige a redirectUri como se menciona en su código para la clase ChallengeResult. Que es Account / ExternalLoginCallback.