Handling Vue Router (history mode) and Webpack external redirects
P粉681400307
2023-08-28 12:13:17
<p>SO Community,</p>
<p>I'm trying to add external authentication to an existing Vue 2 application. The problem I'm having is that when the external IdP redirects back to the Vue application with the path <code>/redirect</code>, the Vue Router doesn't seem to respect the updated path and route to the correct component. In other words, Vue Router will route to the <code>/</code> component instead of the <code>/redirect</code> component. </p>
<p>Vue Router sets <code>mode: 'history'</code> and Webpack sets <code>historyApiFallback: true,</code>. </p>
<h1>Current behavior: </h1>
<ol>
<li>The user navigates to <code>https://localhost:8080/</code> and the <code>Login</code> component is rendered. </li>
<li>The user enters their ID and is redirected to the external IdP. </li>
<li>After successful authentication, the IdP returns to the specified redirect URL: <code>https://localhost:8080/redirect</code></li>
<li>Due to historical mode, Webpack sends the browser to <code>/</code>, which returns the <code>Login</code> component. </li>
<li>In the <code>Login</code> component, <code>mounted()</code> hook check<code>if (window.location.pathname === '/redirect') router.push({ path: '/redirect' });</code></li>
<li>Vue Router goes to the <code>/</code> path instead of <code>/redirect</code> and its components.</li>
</ol>
<h2>技术细节:</h2>
<p>Vue - 2.5.15</p><p>
路由器视图 - 3.0.0</p><p>
Webpack - 4.17.1</p><p>
Webpack 开发服务器 - 3.1.4</p>
<h2><code>webpack.dev.js</code></h2>
<pre class="brush:php;toolbar:false;">devServer: {
historyApiFallback: true,</pre>
<h2><code>router.js</code></h2>
<pre class="brush:php;toolbar:false;">const router = new VueRouter({
mode: 'history',
routes: [
...
{
path: '/redirect',
component: Redirect,
},
{
path: '/',
redirect: () => {
},
...
router.beforeEach((to, from, next) => {
const user = store.state.user.authorizedUser
const toPath = to.path
if (toPath === '/redirect') return
});</pre>
<h2><code>App.vue</code></h2>
<pre class="brush:php;toolbar:false;">new Vue({
el: '#login',
render: h => h(Login),
store,
})</pre>
<h2><code>登录.vue</code></h2>
<pre class="brush:php;toolbar:false;">mounted() {
if (window.location.pathname === '/redirect') router.push({ path: '/redirect' });
}</pre>
<p>请告诉我是否需要提供任何其他细节或代码。提前感谢您的帮助。</p>
So, the problem seems to be with the top-level component
Login
acting as a traffic cop before the router boots up. I had to edit theLogin
component to mount theRedirect
component manually.I don’t recommend this setting.