Search code examples
oauthoauth-2.0google-oauthowinkatana

Why is User.Identity.IsAuthenticated not true after GoogleAuthentication?


I'm trying to debug an issue with OWIN and GoogleAuthentication, everything works on the redirect to google and then google redirects back and my custom GoogleAuthProvider is called and then finally a redirect occurs back to the desired page.

Unfortunately after the redirect back to the desired page, !User.Identity.IsAuthenticated is false so my account controller assumes that it needs to redirect back to google for authentication. My GoogleAuthProvider.Authenticated(GoogleOAuth2AuthenticatedContext context) function is called, and if it appears that the current user is authenticated before the redirect.

What can cause a user to become unauthenticated on a redirect? Why isn't the app setting or reading the authentication value between requests?

Here's my GoogleAuthProvider:

public class GoogleAuthProvider : IGoogleOAuth2AuthenticationProvider
    {
        public void ApplyRedirect(GoogleOAuth2ApplyRedirectContext context)
        {
            context.Response.Redirect(context.RedirectUri);
        }

        public Task Authenticated(GoogleOAuth2AuthenticatedContext context)
        {
            context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
            return Task.FromResult<object>(null);
        }

        public Task ReturnEndpoint(GoogleOAuth2ReturnEndpointContext context)
        {
            return Task.FromResult<object>(null);
        }
    }

Here's my ConfigureOAuth:

public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions
            {
                ClientId = "x",
                ClientSecret = "x",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(GoogleAuthOptions);
}

Solution

  • All your code seems good But what you have to do is to Enable "Google+ API." You can get more help from here http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on

    How to enable At developer console dashboardlook for "Enable API". Click and in the search type Google+ API

    You can enable here.

    Hope this helpsenter image description here