Identity icon indicating copy to clipboard operation
Identity copied to clipboard

Redirect url for external login gets listening address:port on Kestrel

Open Vaiune opened this issue 10 years ago • 16 comments

I've published an 1.1 RTM MVC project to Linux according to the docs. Later, we decided to add external logins to the project. I've read the docs about adding Facebook Login provider to Identity and followed it through, made the facebook app public and callback oauth url is our public domain like docs read on production.

Kestrel listens on localhost:5000 and Nginx is in front of Kestrel on port 80 and 443 for HTTP and HTTPS.

When we try to login via Facebook, it sends a request to Facebook that has the redirect url which is Kestrel listening on to.

If I would change the listening address to our public domain, it would crash because of Nginx. Docs don't say a single thing about this situation.

Another weird thing is, there is also an attention thing about installing Facebook provider Nuget package via "dotnet install" which doesn't exist on either 1.0 or 1.1? I've added it to project.json manually.

Vaiune avatar Nov 21 '16 21:11 Vaiune

If I would change the listening address to our public domain, it would crash because of Nginx.

This doesn't make sense to me. The redirect URL should be pointing to the public endpoint exposed by nginx. If Kestrel is listening on localhost:5000, nothing other than nginx should be sending requests to that port. The redirect url should point to "https://<your public domain>", and nginx should proxy the redirect request to Kestrel on port 5000.

Another weird thing is, there is also an attention thing about installing Facebook provider Nuget package via "dotnet install" which doesn't exist on either 1.0 or 1.1? I've added it to project.json manually.

What doesn't exist? The Microsoft.AspNetCore.Authentication.Facebook package is on Nuget.org and you can install the dotnet command from https://www.microsoft.com/net/download/core.

halter73 avatar Nov 23 '16 18:11 halter73

Sorry, if I mislead you. Nginx sits in front of Kestrel and does its job as a proxy between Kestrel and internet. Kestrel isn't exposed to public. Kestrel just starts to listen on localhost:5000 as default. All I did was according to the official docs.

Enter your base URI with signin-facebook appended into the Valid OAuth Redirect URIs field.

When deploying the site you'll need to register a new public url.

"Valid OAuth Redirect URIs" contains only one entry which is our domain/signin-facebook as it reads on documentation.

The scenario is, the visitor wants to login via Facebook on Account/Login, clicks on Facebook button as it indicates login to the site using your existing FB account, then it should go to Facebook to get consent of the user, right? But the URL that used to request to Facebook has its "redirect_uri" field as http://localhost:5000 which is what Kestrel listens to. If I change Kestrel's listening address via UseUrls() extension the "redirect_uri" field also changes too.

That is our problem. I can't change our Kestrel to listen on port 80 or 443. IMHO, there should be some setting to tell Identity or Auth provider(eg:FB provider package) to use public domain instead of what Kestrel listens to. If there is one, then I missed it.

https://www.facebook.com/v2.6/dialog/oauth?client_id=XXX&scope=public_profile,email&response_type=code

&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fsignin-facebook&state=...

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

I hope you could understand now.

You will need to use NuGet to install the Microsoft.AspNetCore.Authentication.Facebook package if it hasn't already been installed. Alternatively, execute the following commands in your project directory:

dotnet install Microsoft.AspNetCore.Authentication.Facebook

Of course the nuget package exists on NuGeT, and the dotnet command exists :) dotnet install doesn't exist.

Vaiune avatar Nov 23 '16 19:11 Vaiune

Thanks for the clarification. I think I now understand the issue.

The reason that the FB provider package doesn't have a setting to configure the redirect URI is because it uses Request.Scheme and Request.Host to generate the URI. Since the request is forwarded by nginx, the publicly accessible host is in the X-Forwarded-For header and the scheme is in the X-Forwarded-Proto header instead of the Host header.

The fix is to use the the ForwardedHeaders middleware from Microsoft.AspNetCore.HttpOverrides package. You can see how to use it this in this sample. The biggest thing to watch out for is to call app.UseForwardedHeaders before calling app.UseFacebookAuthentication or similar.

This issue seems similar to https://github.com/IdentityServer/IdentityServer4/issues/324.

@Vaiune Were you using the https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction guide to configure nginx? @Rick-Anderson Maybe we should add a tip for configuring the ForwardedHeaders middleware in that guide.

P.S. I think you're right about dotnet install not existing. I've never used it at least. I think the recommended approach is to manually edit your project.json and then dotnet restore

halter73 avatar Nov 23 '16 20:11 halter73

Maybe we should add a tip for configuring the ForwardedHeaders middleware in that guide.

@halter73 can you use the Edit (in browser) feature to add that tip? I'll edit/merge the PR.

Rick-Anderson avatar Nov 23 '16 20:11 Rick-Anderson

The fix is to use the the ForwardedHeaders middleware from Microsoft.AspNetCore.HttpOverrides package. You can see how to use it this in this sample. The biggest thing to watch out for is to call app.UseForwardedHeaders before calling app.UseFacebookAuthentication or similar.

This ForwardedHeaders middleware fixed the issue for us. But unfortunately, we have another problem now. The error happens after the consent had given by user on Facebook and redirected back to us.

InvalidOperationException: No authentication handler is configured to handle the scheme: Identity.External Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager+d__14.MoveNext()

What did I miss here? I put app.UseForwardedHeaders before app.UseFacebookAuthentication and finally app.UseMvc in Configure method.

Vaiune avatar Nov 23 '16 21:11 Vaiune

@halter73 @HaoK any of you can help with the exception:

InvalidOperationException: No authentication handler is configured to handle the scheme: Identity.External
Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager+d__14.MoveNext()

divega avatar Nov 23 '16 21:11 divega

Looks like its missing a use identity.

On Nov 23, 2016, at 1:53 PM, Diego Vega [email protected] wrote:

@halter73 @HaoK any of you can help with the exception:

InvalidOperationException: No authentication handler is configured to handle the scheme: Identity.External Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager+d__14.MoveNext() — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

HaoK avatar Nov 24 '16 00:11 HaoK

@mikaelm12 Could you edit https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction and maybe https://docs.microsoft.com/en-us/aspnet/core/publishing/apache-proxy to describe how to use HttpOverrides ?

halter73 avatar Nov 28 '16 23:11 halter73

@HaoK @halter73 I forgot to mention that I figured it out. It works perfectly fine now on Ubuntu 16.04 Nginx 1.11.6 HTTP2 & SSL Looks like UseIdentity() should come first before any other external providers. Maybe this should be noted on the docs as well?

Thanks for all of your help.

Vaiune avatar Nov 29 '16 00:11 Vaiune

@Vaiune would you mind doing an edit in browser PR with your suggestion?

Rick-Anderson avatar Nov 29 '16 00:11 Rick-Anderson

@Rick-Anderson Sure but I'm not sure which page/pages it should go. I think it should be noted on https://docs.microsoft.com/en-us/aspnet/core/security/authentication/sociallogins after 'Setup login providers required by your application' and before 'Optionally set password' where supported external providers listed?

Vaiune avatar Nov 29 '16 00:11 Vaiune

@halter73 is that the right place to add this note?

Rick-Anderson avatar Nov 29 '16 01:11 Rick-Anderson

@Rick-Anderson I'm not sure what the best place to put the note is. To me it makes the most sense in https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction or anywhere else we provide a guide to setting up a reverse proxy that isn't IIS.

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/sociallogins is probably a good second place to leave a note, since social logins are probably the most immediate thing people see fail if they forgot to set up HttpOverrides.

halter73 avatar Nov 29 '16 22:11 halter73

Hi everyone,

can somebody explain why UseIdentity() call is required for reverse-proxy setup? Here is the code:

public static IApplicationBuilder UseIdentity(this IApplicationBuilder app)
    {
      if (app == null)
        throw new ArgumentNullException("app");
      if (app.ApplicationServices.GetService<IdentityMarkerService>() == null)
        throw new InvalidOperationException(Microsoft.AspNetCore.Identity.Resources.MustCallAddIdentity);
      IdentityOptions identityOptions = app.ApplicationServices.GetRequiredService<IOptions<IdentityOptions>>().Value;
      app.UseCookieAuthentication(identityOptions.Cookies.ExternalCookie);
      app.UseCookieAuthentication(identityOptions.Cookies.TwoFactorRememberMeCookie);
      app.UseCookieAuthentication(identityOptions.Cookies.TwoFactorUserIdCookie);
      app.UseCookieAuthentication(identityOptions.Cookies.ApplicationCookie);
      return app;
    }

There is nothing special there except check for "IdentityMarkerService" registration, which is registered inside AddIdentity<>() call. "AddIdentity" is also not required by itself for reverse-proxy, except for this line of code:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

But even if I register this service by myself, I still get wrong redirect URL :(

My setup seems to be correct (and it works fine without reverse-proxy):

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      app.UseForwardedHeaders(new ForwardedHeadersOptions
                              {
                                ForwardedHeaders = ForwardedHeaders.All
                              });
      app.UseHttpMethodOverride();
      
      app.UseFacebookAuthentication(new FacebookOptions
                                    {
                                      AppId = Configuration.GetValue<string>("Facebook:appid"),
                                      AppSecret = Configuration.GetValue<string>("Facebook:appsecret"),
                                      Scope = {"email", "user_photos"},
                                      Fields = {"first_name", "last_name", "middle_name", "gender", "id", "email", "birthday", "location"},
                                      SignInScheme = "FacebookCookie",
                                      Events = new OAuthEvents
                                               {
                                                 OnCreatingTicket = OnCreatingTicket
                                               }

                                    });

      app.UseCookieAuthentication(new CookieAuthenticationOptions
                                  {
                                    AuthenticationScheme = "FacebookCookie",
                                    CookieHttpOnly = true,
                                    LoginPath = new PathString("/Account/Login/"),
                                    AccessDeniedPath = new PathString("/Account/Forbidden/")
                                  });

HTTP headers also seem to contain all required information:

image

usarskyy avatar Jul 20 '17 07:07 usarskyy

@usarskyy I think you are correct. There is still confusion around why you would call UseIdentity is this scenario.

dcarr42 avatar Jul 20 '17 12:07 dcarr42

@Vaiune did you use AddIdentity<>() before adding UseIdentity()? It seems to be the requirement right now. Unfortunately in my case it will require additional refactoring because authentication was built long time ago and it doesn't use ASP.NET Identity. That's why I'm trying to find another way that doesn't involve all this Identity stuff.

usarskyy avatar Jul 20 '17 21:07 usarskyy