ASP.NET MVC URL being over written when going to External from Controller

Viewed 57

Problem is when I run this code the controller does not fire the the HttpContext call. If fact the URL changes from http://localhost:xxxxx/Account/LogOn to http://localhost:xxxxx/Account/LogOn?ReturnUrl=%2fAccount%2fSignIn in stead of going to AD B2C active directory. The code works in test applications, without some of the Global.ascx settings. What could be causing this? The test application uses Global.ascx

protected void Application_Start()
    {
        
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

 
Controller 
   

    public void SignIn()
                {
                    if (!Request.IsAuthenticated)
                    {
                        // To execute a policy, you simply need to trigger an OWIN challenge.
                        // You can indicate which policy to use by specifying the policy id as the AuthenticationType
                        HttpContext.GetOwinContext().Authentication.Challenge(
                            new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignInPolicyId); 
                        
                    }
                }

   Web Config

    <add key="ida:Tenant" value="{tenant}.onmicrosoft.com" />
    <add key="ida:ClientId" value="xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" />
    <add key="ida:MetadataAddress" value="https://{tenant}.b2clogin.com/{0}/{1}/v2.0/.well-known/openid-configuration" />
    <add key="ida:AadInstance" value="https://{Tenant}.b2clogin.com/{0}/{1}/v2.0" />
    <add key="ida:ResetPassword" value="password_reset" />
    <add key="ida:UserProfilePolicyId" value="profile_edit" />
    <add key="ida:SignInPolicyId" value="signup_signin" />

Startup class

   

     private static readonly string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
                private static readonly string aadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
                private static readonly string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
                private static readonly string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
                private static readonly string metadataAddress= ConfigurationManager.AppSettings["ida:MetadataAddress"];
                // B2C policy identifiers
                public static string SignInPolicyId = ConfigurationManager.AppSettings["ida:SignInPolicyId"];
                public static string ResetPasswordPolicyId = ConfigurationManager.AppSettings["ida:ResetPassword"];
                public static string ProfilePolicyId = ConfigurationManager.AppSettings["ida:UserProfilePolicyId"];
        
                public void Configuration(IAppBuilder app)
                {
                    ConfigureAuth(app);
                }
        
                
                public void ConfigureAuth(IAppBuilder app)
                {
                    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        
                    app.UseCookieAuthentication(new CookieAuthenticationOptions());
        
                    // Configure OpenID Connect middleware for each policy
                    
                    app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ResetPasswordPolicyId));
                    app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
                    app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
                }
        
                // Used for avoiding yellow-screen-of-death
                private Task AuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
                {
                    notification.HandleResponse();
                    if (notification.Exception.Message == "access_denied")
                    {
                        notification.Response.Redirect("/");
                    }
                    else
                    {
                        notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
                        
                    }
        
                    return Task.FromResult(0);
                }
        
                private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
                {
                    var  authenication = new OpenIdConnectAuthenticationOptions
                    {
        
                        // For each policy, give OWIN the policy-specific metadata address, and
                        // set the authentication type to the id of the policy
                        MetadataAddress = String.Format(metadataAddress, tenant, policy),
                        AuthenticationType= policy,
                        Authority = string.Format(aadInstance, tenant, policy), 
                        
                        ClientId = clientId,
                        
                        RedirectUri = redirectUri,
                        PostLogoutRedirectUri = redirectUri,
                        Notifications = new OpenIdConnectAuthenticationNotifications
                        {
                            AuthenticationFailed = AuthenticationFailed,
                            RedirectToIdentityProvider=OnRedirectToIdentityProvider
                            
                        },
                        Scope = OpenIdConnectScope.OpenId,
                        // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        
                        // This piece is optional - it is used for displaying the user's name in the navigation bar.
                        TokenValidationParameters = new TokenValidationParameters
                        {
                            NameClaimType = "name",
                            SaveSigninToken = true //important to save the token in boostrapcontext
                        },
                    };
        
                    return authenication;
                }
                private Task 
     OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
                {
                    /*var policy = notification.OwinContext.Get<string>("Policy");*/
        
                    notification.ProtocolMessage.Scope = OpenIdConnectScope.OpenId;
                    notification.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
                    notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower();
                    
                    return Task.FromResult(0);
                }
    
    Global.ascx
     
    
    MvcHandler.DisableMvcResponseHeader = true;
        UnityConfig.RegisterComponents();
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ThreadPool.SetMinThreads(minThreads, minThreads);
0 Answers
Related