Индекс должен быть больше или равен нулю при использовании B2 C Логин - PullRequest
0 голосов
/ 03 апреля 2020

Итак, я пытаюсь создать портал для проекта и использовать B2 C в качестве системы входа в систему, поскольку это проще, чем создать собственную систему и постоянно работать с SQL на ней.

Я использую этот учебник как способ узнать, как его сделать.

Теперь, когда я пытаюсь запустить его, я получаю сообщение об ошибке в моем Startup.auth. cs class.

Это код, который я использую:

Startup.Auth.cs
    //  public partial class Startup
    {
        // Calling the key values from the web.config section
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
        private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
    // Concatenate the aadInstance, tenant to forn authority value
    private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    /*
     * Configure the method
     * The method is used to build an authentication system that lets me be able to log in and out with B2C
     */
    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.OwinContext.Response.Redirect("/Home/Index");
                        return Task.FromResult(0);
                    }
                }
            });

    }

Startup.cs:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}

И в своем web.config я добавил TenantId , ClientId, ClientSecret, AadInstance, REdirectUri и значения пароля для входа в систему / регистрации и сброса пароля в

генерирует эту ошибку, когда я пытаюсь запустить ее локально:

"System.FormatException: 'Индекс (на основе нуля) должен быть больше или равен нулю и меньше размера списка аргументов.' "

1 Ответ

0 голосов
/ 13 апреля 2020

Образец, на который вы ссылались, - это образец аутентификации Azure AD.

Вам нужна политика в URL авторизации.

Вот b2 c с ASP. NET MVC Пример веб-приложения для справки. .

Класс запуска

public class Startup
    {
        // App config settings
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

        // B2C policy identifiers
        public static string SignUpPolicyId = ConfigurationManager.AppSettings["ida:SignUpPolicyId"];
        public static string SignInPolicyId = ConfigurationManager.AppSettings["ida:SignInPolicyId"];
        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(SignUpPolicyId));
            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)
        {
            return 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(aadInstance, tenant, policy),
                AuthenticationType = policy,

                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed
                },
                Scope = "openid",
                ResponseType = "id_token",

                // 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
                }
            };
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...