Перенаправление не происходит с IdentityServer4 после входа в клиентское приложение vuejs с неявным большим потоком

Я получаю исключение ниже - в неявном режиме с vue.js

Этот сайт недоступен % 252Flogin% 26response_type% 3Did_token% 2520token% 26scope% 3Dopenid% 2520profile% 2520courses% 2520roles% 2520country% 2520GPSSchoolAPI% 26state% 3D5b7f679b185642db87a745f649dab48f% 26nonce% 3D9f222f460a974434a6d0a7179d79765a»отн = "NOFOLLOW noreferrer"> HTTP: // локальный: 5000 / Account / Логин? ReturnUrl =% 2Fconnect% 2Fauthorize% 2Fcallback% 3Fclient_id% 3DVuejs% 26redirect_uri% 3Dhttp% 253A% 252F% 252Flocalhost% 253A8484% 252Flogin% 26response_type% 3Did_token% 2520token% 26scope% 3Dopenid% 2520profile% 2520courses% 2520roles% 2520country% 2520GPSSchoolAPI% 26state% 3D5b7f679b185642db87a745f649dab48f % 26nonce% 3D9f222f460a974434a6d0a7179d79765a может быть временно недоступен или, возможно, навсегда переехал на новый веб-адрес. ERR_RESPONSE_HEADERS_TOO_BIG

Войти в консоль

Executed action method TIS.IdentityServer.Controllers.Account.AccountController.Login (TIS.IdentityServer), returned result Microsoft.AspNetCore.Mvc.RedirectResult in 65364.2974ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.RedirectResultExecutor[1]
Executing RedirectResult, redirecting to /connect/authorize/callback?client_id=Vuejs&redirect_uri=http%3A%2F%2Flocalhost%3A8484%2Flogin&response_type=id_token%20token&scope=openid%20profile%20courses%20roles%20country%20GPSSchoolAPI&state=5b7f679b185642db87a745f649dab48f&nonce=9f222f460a974434a6d0a7179d79765a.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action TIS.IdentityServer.Controllers.Account.AccountController.Login (TIS.IdentityServer) in 65380.1296ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TIS.IdentityServer.Controllers.Account.AccountController.Login (TIS.IdentityServer)'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 65421.3075ms 302

конфигурация

export const oidcSettings = {
    authority: 'http://localhost:5000',
    client_id: 'Vuejs',
    redirect_uri: 'http://localhost:8484/login',
    response_type: 'id_token token',
    scope:'openid profile courses roles country GPSSchoolAPI',
    post_logout_redirect_uri: 'http://localhost:8484/index.html',
    //userStore: new Oidc.WebStorageStateStore(),
    loadUserInfo: true,
    filterProtocolClaims: true
  }

посадочный компонент

<script>
import { mapActions, mapGetters } from 'vuex'
    export default {
        name: "login",
        data: () => {
            return {
                IsLogin: true,
                IsForgotPassword: false,
                //loginleftbg: 'http://localhost/my-project2/src/assets/images/login_side_bg.png',
                LogoUrl: process.env.ROOT_API_IMG + 'logo.png',
                regionalIcon: process.env.userTypeIconPath + 'regional-head.png',
                ceoIcon: process.env.userTypeIconPath + 'ceo.png',
                principalIcon: process.env.userTypeIconPath + 'principal.png',
                teacherIcon: process.env.userTypeIconPath + 'teacher.png',
                studentIcon: process.env.userTypeIconPath + 'student.png',
                parentIcon: process.env.userTypeIconPath + 'parent.png',
                governmentIcon: process.env.userTypeIconPath + 'government.png'

            }
        },
        methods: {
            NavigateTo(name, uuid) {
                this.$router.push({name: name, params: {uuid: uuid}});
            },
            
             ...mapActions( [
                'oidcSignInCallback'
             ])

        },
         computed:{
      ...mapGetters([
        'oidcUser'
      ])
    },
    created(){
       
       this.oidcSignInCallback()
      .then((redirectPath) => {
         
    // this.$router.push({name: 'admin'})
     // this.redirectToUser('admin','admin')
      })
      .catch((err) => {
        console.error("hjk"+err)
        this.$router.push('/oidc-callback-error') // Handle errors any way you want
      })
    },
    mounted(){
       
    }
    };
</script>
<div>
                    <h1>Login successful</h1>
                    <p>Your browser should be redirected soon</p>
                   <!-- <p v-if="oidcUser">User: {{oidcUser}} </p>-->
                    
                       
                 </div>

Я использую базовую идентификацию Asp.net для управления пользователями, и для этого я использую следующую конфигурацию.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
       // services.AddSpaStaticFiles();
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false)
            .Build();
        string connectionStringData = config.GetSection("ConnectionStrings:identityServerDataDB").Value;
        string connectionStringUser = config.GetSection("ConnectionStrings:tisUserDataDB").Value;
        var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
        // for user add the DBcontext.
        services.AddDbContext<ApplicationDbContext>(option => {
            option.UseSqlServer(connectionStringUser);
        });
        services.AddIdentity<ApplicationUser,IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, TISUserClaimsPrincipalFactory>();
       // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);

        services.AddIdentityServer(options=> {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                })
                .AddDeveloperSigningCredential()

                //.AddTestUsers(Config.GetUsers())
                .AddAspNetIdentity<ApplicationUser>()

                // Configuration Store : Clients and Resource
                .AddConfigurationStore(option =>
                {
                    option.ConfigureDbContext = b => b.UseSqlServer(connectionStringData, sql => sql.MigrationsAssembly(migrationAssembly));
                })
                // Operational Store: tokens concent code etc.
                .AddOperationalStore(option => {
                    option.ConfigureDbContext = b => b.UseSqlServer(connectionStringData, sql => sql.MigrationsAssembly(migrationAssembly));
                });


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        InitializeIdentityServerDatabase(app);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseDefaultFiles();
        app.UseIdentityServer();
        // app.UseSpaStaticFiles();


        app.UseMvcWithDefaultRoute();

    }

person Santosh Jha    schedule 29.09.2019    source источник


Ответы (2)


Я считаю, что вы используете страницу входа в свое приложение. В таком случае вам необходимо использовать поток паролей владельца ресурса http://docs.identityserver.io/en/latest/topics/grant_types.html

(or)

Если вы используете страницу входа на сервер идентификации (пример приложения MVC с сервера идентификации), вам необходимо сделать ее доступной в «/ Account / Login» по умолчанию.

(or)

Если вам нужна собственная страница входа для сервера идентификации, вы можете настроить через

services.AddIdentityServer(setupAction =>
{
    setupAction.UserInteraction.LoginUrl = "/Account#Login";
    setupAction.UserInteraction.LogoutUrl = "/Account#Logout";
    setupAction.UserInteraction.ErrorUrl = "/Account#Error";
})
person Aypn    schedule 02.10.2019
comment
Сэр, спасибо за ответ. проблема возникает после входа в систему, когда необходимо перенаправить в клиентское приложение. 1. Использование экрана входа в IdentityServer4 с основным идентификатором Asp.net. 2. Неявный режим, как это приложение Vue.Js - включил конфигурацию в сообщение. 3. Я использую Vuex с OIDC. 4. Исключение составляет конечная точка / подключение / авторизация / обратный вызов. - person Santosh Jha; 03.10.2019

проблема была в файлах cookie, размер увеличивался из-за данных, после его уменьшения он работал.

person Santosh Jha    schedule 13.10.2019
comment
Не могли бы вы рассказать нам, как вы уменьшили размер файлов cookie? Или это были дополнительные данные, принадлежащие вашим приложениям? - person Babak; 13.08.2020