Reverse proxy with openid connect redirection

依然范特西╮ 提交于 2019-12-05 22:00:06

After a long search this is the fix:

The OWIN middleware UseOpenIdConnectAuthentication has a property Notifications in the Options property. This Notifications property has a func SecurityTokenValidated. In this function you can modify the Redirect Uri.

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
    Authority = "https://idp.io",
    ClientId = "clientid",
    RedirectUri = "https://mywebsite.io",
    ResponseType = "code id_token token",
    Scope = "openid profile",
    SignInAsAuthenticationType = "Cookies",
    UseTokenLifetime = false,
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
        SecurityTokenValidated = notification =>
        {
            notification.AuthenticationTicket.Properties.RedirectUri = RewriteToPublicOrigin(notification.AuthenticationTicket.Properties.RedirectUri);
            return Task.CompletedTask;
        }
    }
});

This is the function which rewrites the url to the public origin:

private static string RewriteToPublicOrigin(string originalUrl)
{
    var publicOrigin = ConfigurationManager.AppSettings["app:identityServer.PublicOrigin"];
    if (!string.IsNullOrEmpty(publicOrigin))
    {
        var uriBuilder = new UriBuilder(originalUrl);
        var publicOriginUri = new Uri(publicOrigin);
        uriBuilder.Host = publicOriginUri.Host;
        uriBuilder.Scheme = publicOriginUri.Scheme;
        uriBuilder.Port = publicOriginUri.Port;
        var newUrl = uriBuilder.Uri.AbsoluteUri;

        return newUrl;
    }

    return originalUrl;
}

Now the OpenIdConnect redirects the user to the public url instead of the non-public webserver url.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!