2017-08-25 202 views
0

我有一個項目,我已經開始構建,並且想要使我們成爲Azure AD B2C - 我遵循了一些教程和通過從頭創建一個新的MVC應用程序進行測試,然後我得到它的工作,但是,當我嘗試將其實施到我現有的項目中,然後它不會重定向到SignIn/SignUp頁面(這是login.microsoftonline.com ... )網址。我知道我的代碼可以重定向到這個URL,因爲它對我創建的新項目進行測試,所以不知道爲什麼它不會在我現有的項目上。Azure AD B2C - 沒有重定向到登錄/註冊頁面(login.microsoftonline.com ...)

這是我的web.config:

<add key="ida:Tenant" value="Name.onmicrosoft.com" /> 
<add key="ida:ClientId" value="GUID" /> 
<add key="ida:ClientSecret" value="Secret" /> 
<add key="ida:AadInstance" value="https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/.well-known/openid-configuration" /> 
<add key="ida:RedirectUri" value="https://localhost:44382/" /> 
<add key="ida:SignUpSignInPolicyId" value="B2C_1_SiUpIn" /> 
<add key="ida:EditProfilePolicyId" value="B2C_1_SiPe" /> 
<add key="ida:ResetPasswordPolicyId" value="B2C_1_SSPR" /> 

的ActionLink:

@Html.ActionLink("Sign up/Sign in", "SignUpSignIn", "Account", routeValues: null, htmlAttributes: new { id = "signUpSignInLink" }) 

這是SignUpSignIn功能我打電話:

[AllowAnonymous] 
     public void SignUpSignIn() 
     { 
      // Use the default policy to process the sign up/sign in flow 
      if (!Request.IsAuthenticated) 
      { 
       HttpContext.GetOwinContext().Authentication.Challenge(); 
       return; 
      } 

      Response.Redirect("/"); 
     } 

下面是從我的代碼啓動:

public partial class Startup 
    { 
     // App config settings 
     public static string ClientId = ConfigurationManager.AppSettings["ida:ClientId"]; 
     public static string ClientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; 
     public static string AadInstance = ConfigurationManager.AppSettings["ida:AadInstance"]; 
     public static string Tenant = ConfigurationManager.AppSettings["ida:Tenant"]; 
     public static string RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; 
     public static string ServiceUrl = ConfigurationManager.AppSettings["api:TaskServiceUrl"]; 

     // B2C policy identifiers 
     public static string SignUpSignInPolicyId = ConfigurationManager.AppSettings["ida:SignUpSignInPolicyId"]; 
     public static string EditProfilePolicyId = ConfigurationManager.AppSettings["ida:EditProfilePolicyId"]; 
     public static string ResetPasswordPolicyId = ConfigurationManager.AppSettings["ida:ResetPasswordPolicyId"]; 

     public static string DefaultPolicy = SignUpSignInPolicyId; 

     // API Scopes 
     public static string ApiIdentifier = ConfigurationManager.AppSettings["api:ApiIdentifier"]; 
     public static string ReadTasksScope = ApiIdentifier + ConfigurationManager.AppSettings["api:ReadScope"]; 
     public static string WriteTasksScope = ApiIdentifier + ConfigurationManager.AppSettings["api:WriteScope"]; 
     public static string[] Scopes = new string[] { ReadTasksScope, WriteTasksScope }; 

     // OWIN auth middleware constants 
     public const string ObjectIdElement = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; 

     // Authorities 
     public static string Authority = String.Format(AadInstance, Tenant, DefaultPolicy); 

     /* 
     * Configure the OWIN middleware 
     */ 
     public void ConfigureAuth(IAppBuilder app) 
     { 
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 

      app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

      app.UseOpenIdConnectAuthentication(
       new OpenIdConnectAuthenticationOptions 
       { 
        // Generate the metadata address using the tenant and policy information 
        MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy), 

        // These are standard OpenID Connect parameters, with values pulled from web.config 
        ClientId = ClientId, 
        RedirectUri = RedirectUri, 
        PostLogoutRedirectUri = RedirectUri, 

        // Specify the callbacks for each type of notifications 
        Notifications = new OpenIdConnectAuthenticationNotifications 
        { 
         RedirectToIdentityProvider = OnRedirectToIdentityProvider, 
         AuthorizationCodeReceived = OnAuthorizationCodeReceived, 
         AuthenticationFailed = OnAuthenticationFailed, 
        }, 

        // Specify the claims to validate 
        TokenValidationParameters = new TokenValidationParameters 
        { 
         NameClaimType = "name" 
        }, 

        // Specify the scope by appending all of the scopes requested into one string (separated by a blank space) 
        Scope = $"openid profile offline_access {ReadTasksScope} {WriteTasksScope}" 
       } 
      ); 
     } 

     /* 
     * On each call to Azure AD B2C, check if a policy (e.g. the profile edit or password reset policy) has been specified in the OWIN context. 
     * If so, use that policy when making the call. Also, don't request a code (since it won't be needed). 
     */ 
     private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification) 
     { 
      var policy = notification.OwinContext.Get<string>("Policy"); 

      if (!string.IsNullOrEmpty(policy) && !policy.Equals(DefaultPolicy)) 
      { 
       notification.ProtocolMessage.Scope = OpenIdConnectScopes.OpenId; 
       notification.ProtocolMessage.ResponseType = OpenIdConnectResponseTypes.IdToken; 
       notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(DefaultPolicy.ToLower(), policy.ToLower()); 
      } 

      return Task.FromResult(0); 
     } 

     /* 
     * Catch any failures received by the authentication middleware and handle appropriately 
     */ 
     private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification) 
     { 
      notification.HandleResponse(); 

      // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page 
      // because password reset is not supported by a "sign-up or sign-in policy" 
      if (notification.ProtocolMessage.ErrorDescription != null && notification.ProtocolMessage.ErrorDescription.Contains("AADB2C90118")) 
      { 
       // If the user clicked the reset password link, redirect to the reset password route 
       notification.Response.Redirect("/Account/ResetPassword"); 
      } 
      else if (notification.Exception.Message == "access_denied") 
      { 
       notification.Response.Redirect("/"); 
      } 
      else 
      { 
       notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message); 
      } 

      return Task.FromResult(0); 
     } 


     /* 
     * Callback function when an authorization code is received 
     */ 
     private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification) 
     { 
      // Extract the code from the response notification 
      var code = notification.Code; 

      string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 
      TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); 
      ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null); 
      try 
      { 
       AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes); 
      } 
      catch (Exception ex) 
      { 
       //TODO: Handle 
       throw; 
      } 
     } 
    } 

當我點擊這個ActionLink的它擊中的控制器,但隨後並沒有重定向,它只是返回這個網址:

https://localhost:44382/account/login?ReturnUrl=%2faccount%2fsignupsignin

有一件事不得不提,是我購買,我使用的模板 - 不知道這可能會有什麼影響 - 我完全難住,不知道還有什麼我可以看看....

如果您需要任何我沒有發佈,請讓我知道。

如果任何人能夠幫助我在正確的方向,我將不勝感激。

謝謝!

+0

你能分享你的啓動代碼來配置auth嗎? [參考示例代碼](https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/blob/master/TaskWebApp/App_Start/Startup.Auth.cs) – spottedmahn

+0

感謝您的回覆。我已經添加了啓動代碼。 – AxleWack

+0

np。那有用嗎? – spottedmahn

回答

0

因此,不幸的是我沒有找到一個解決問題的具體解決方案,因爲我無法確定問題到底是什麼。但是,我通過創建一個全新項目來解決問題,並將我購買的模板(這是一個mvc項目)中的項目移動到新創建的項目中。因爲需要修復因爲此問題而發生的任何錯誤,所以我需要忍受痛苦,但它最終還是在工作。購買的模板中顯然有一些導致問題的原因。

所以只是爲了給出一些上下文 - 我購買的模板有不同的框架,你可以使用(MVC,PHP,Angular等),並且我使用了包含模板的MVC項目,並且我只是繼承了該MVC項目,所以我假設該項目中有某些內容導致了問題。

相關問題