使用隐式大流程登录到客户端 vuejs 应用程序后,不会从 IdentityServer4 发生重定向

Posted

技术标签:

【中文标题】使用隐式大流程登录到客户端 vuejs 应用程序后,不会从 IdentityServer4 发生重定向【英文标题】:Redirection not happening from IdentityServer4 after Login to client vuejs application with Implicit grand flow 【发布时间】:2020-01-28 21:01:50 【问题描述】:

我在 vue.js 的隐式模式下遇到异常

无法访问此站点http://localhost:5000/Account/Login?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 core Identity 进行用户管理,配置如下

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();

    

【问题讨论】:

【参考方案1】:

我相信您正在使用您的应用程序的登录页面。如果是这样,您需要使用资源所有者密码流程 http://docs.identityserver.io/en/latest/topics/grant_types.html

(或)

如果您使用身份服务器的登录页面(来自身份服务器的示例 MVC 应用程序),您需要按照默认设置在“/Account/Login”处提供它

(或)

如果你想要自己的身份服务器登录页面,可以通过配置

services.AddIdentityServer(setupAction =>

    setupAction.UserInteraction.LoginUrl = "/Account#Login";
    setupAction.UserInteraction.LogoutUrl = "/Account#Logout";
    setupAction.UserInteraction.ErrorUrl = "/Account#Error";
)

【讨论】:

先生,谢谢您的回复。问题出现在登录后,当它需要重定向到客户端应用程序时。 1. 使用带有 Asp.net 核心身份的 IdentityServer4 登录屏幕。 2.隐式模式,因为它是 Vue.Js 应用程序 - 在帖子中包含了配置。 3. 我正在使用带有 OIDC 的 Vuex。 4. 异常在 /connect/authorize/callback 端点。【参考方案2】:

问题出在 Cookies 中,由于数据,大小正在增加,减少后,它起作用了。

【讨论】:

您能告诉我们您是如何减小 cookie 的大小的吗?还是属于您的应用程序的一些额外数据?

以上是关于使用隐式大流程登录到客户端 vuejs 应用程序后,不会从 IdentityServer4 发生重定向的主要内容,如果未能解决你的问题,请参考以下文章

无法使用客户端(隐式)身份验证登录 Instagram

如何在 SPA 中实现 OAuth 隐式流?

登录 vuejs 后重新渲染导航栏

如何在不登录的情况下从 Instagram 获取 oauth 2 访问令牌(隐式流程)?

如何确定用户是不是仍在使用 PingFederate OpenID Connect 隐式客户端流登录?

Instagram 客户端(隐式)身份验证不可用?