Error de demostración no autorizada de Microsoft B2C Azure

 C Programming >> Programación C >  >> Tags >> Azure
Error de demostración no autorizada de Microsoft B2C Azure

La solución para el error de demostración no autorizada de Microsoft B2C Azure
se proporciona a continuación:

Estoy tratando de aprender ASP.Net con el flujo de inicio de sesión/registro de Azure AD B2C. Estoy ejecutando la demostración aquí:

https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-web-api-dotnet?tabs=app-reg-ga

El código C# para la demostración se puede descargar desde https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/archive/master.zip

Revisé toda la demostración desde el principio y completé todos los requisitos previos.

Ahora estoy en el punto en el que inicié sesión con éxito y cuando hago clic en el enlace Lista de tareas pendientes mientras depuraba la aplicación, obtengo un error de Usuario no autorizado (404).

Pido disculpas de antemano si no estoy explicando muy bien lo que creo que estoy viendo, ya que soy muy nuevo en Azure y la programación web. Me siento más cómodo con las aplicaciones de escritorio de Windows que interactúan con SQL Server, pero estoy tratando de ampliar mis conocimientos, así que tengan paciencia conmigo.

Como dije antes, puedo iniciar sesión correctamente en la aplicación, lo que creo que sucede en el proyecto TaskWebApp.

Aquí está el código donde ocurre el error, que se encuentra en TasksController.cs en el proyecto TaskWebApp:

namespace TaskWebApp.Controllers
{
    [Authorize]
    public class TasksController : Controller
    {
        private readonly string apiEndpoint = Globals.ServiceUrl + "/api/tasks/";

        // GET: Makes a call to the API and retrieves the list of tasks
        public async Task<ActionResult> Index()
        {
            try
            {
                // Retrieve the token with the specified scopes
                var scope = new string[] { Globals.ReadTasksScope };
                
                IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
                var accounts = await cca.GetAccountsAsync();
                AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault()).ExecuteAsync();
                
                HttpClient client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);

                // Add token to the Authorization header and make the request
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                // Handle the response
                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        string responseString = await response.Content.ReadAsStringAsync();
                        JArray tasks = JArray.Parse(responseString);
                        ViewBag.Tasks = tasks;
                        return View();
                    case HttpStatusCode.Unauthorized:
                        return ErrorAction("Please sign in again. " + response.ReasonPhrase);
                    default:
                        return ErrorAction("Error. Status code = " + response.StatusCode + ": " + response.ReasonPhrase);
                }
            }
            catch (MsalUiRequiredException ex)
            {
                /*
                    If the tokens have expired or become invalid for any reason, ask the user to sign in again.
                    Another cause of this exception is when you restart the app using InMemory cache.
                    It will get wiped out while the user will be authenticated still because of their cookies, requiring the TokenCache to be initialized again
                    through the sign in flow.
                */
                return new RedirectResult("/Account/SignUpSignIn?redirectUrl=/Tasks");
            }
            catch (Exception ex)
            {
                return ErrorAction("Error reading to do list: " + ex.Message);
            }
        }

El código de estado de respuesta en la instrucción Switch es 404.

Cuando depuro, esto es lo que veo:

var scope devuelve https://ShoppingCartB2C.onmicrosoft.com/tasks/demo.read

cca devuelve (cuestiono el formato de la propiedad Authority):

las cuentas no devuelven nada. Una cuenta de 0.

Creo que 0 cuentas es el problema.

Cuando trato de obtener un resultado, va al bloque catch.

Aquí está el Web.config para el proyecto TaskWebApp:

<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:Tenant" value="ShoppingCartB2C.onmicrosoft.com" />
    <!--MSAL cache needs a tenantId along with the user's objectId to function. It retrieves these two from the claims returned in the id_token. 
        As tenantId is not guaranteed to be present in id_tokens issued by B2C unless the steps listed in this 
        document (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AAD-B2C-specifics#caching-with-b2c-in-msalnet). 
        If you are following the workarounds listed in the doc and tenantId claim (tid) is available in the user's token, then please change the 
        code in <ClaimsPrincipalsExtension.cs GetB2CMsalAccountId()> to let MSAL pick this from the claims instead -->
    <add key="ida:TenantId" value="db1b052a-415c-4604-887c-e27b59860001" />
    <add key="ida:ClientId" value="975f1457-e3e2-4cb8-b069-6b0b6b46611d" />
    <add key="ida:ClientSecret" value="Gw4.3o-DRDr.j_828H-JMfsk_Jd1d-jQ5p" />
    <add key="ida:AadInstance" value="https://ShoppingCartB2C.b2clogin.com/tfp/{0}/{1}" />
    <add key="ida:RedirectUri" value="https://localhost:44316/" />
    <add key="ida:SignUpSignInPolicyId" value="B2C_1_signupsignin1" />
    <add key="ida:EditProfilePolicyId" value="b2c_1_profileediting1" />
    <add key="ida:ResetPasswordPolicyId" value="b2c_1_passwordreset1" />
    <add key="api:TaskServiceUrl" value="https://localhost:44332/" />
    <!-- The following settings is used for requesting access tokens -->
    <add key="api:ApiIdentifier" value="https://ShoppingCartB2C.onmicrosoft.com/tasks/" />
    <add key="api:ReadScope" value="demo.read" />
    <add key="api:WriteScope" value="demo.write" />
  </appSettings>

Y para el proyecto TaskService:

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:AadInstance" value="https://ShoppingCartB2C.b2clogin.com/{0}/{1}/v2.0/.well-known/openid-configuration" />
    <add key="ida:Tenant" value="ShoppingCartB2C.onmicrosoft.com" />
    <add key="ida:ClientId" value="975f1457-e3e2-4cb8-b069-6b0b6b46611d" />
    <add key="ida:SignUpSignInPolicyId" value="B2C_1_signupsignin1" />
    <!-- The following settings is used for requesting access tokens -->
    <add key="api:ReadScope" value="demo.read" />
    <add key="api:WriteScope" value="demo.write" />
  </appSettings>

Si desea capturas de pantalla de Azure o tiene preguntas sobre cómo se configura, no dude en preguntar.

No me preocupa exponer los secretos de los clientes o AppId porque solo estoy siguiendo una demostración. Esta nunca será una aplicación de producción.

No he realizado ninguna modificación de código en la demostración. Gracias por tu ayuda.

Editar:Mostrar permisos de API