【问题标题】:Angular 4 context lost after authentication身份验证后丢失Angular 4上下文
【发布时间】:2017-11-30 21:44:36
【问题描述】:

我正在使用 ng2-adal 进行身份验证。 Angular 4 路由在身份验证后丢失。在运行项目时,主页 URL 为:'http://localhost:31334/index.html/home'。身份验证成功后,我导航到路由:this.router.navigate(["/upload"])。但是,在成功验证后,浏览器将 url 显示为:http://localhost:31334/upload。结果,页面 CSS 丢失并且页面无法正常显示。 app.route.ts 文件如下所示:

export const router: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'upload', component: UploadComponent },
    { path: 'explore', component: ExploreComponent }
];

export const routes: ModuleWithProviders = RouterModule.forRoot(router);

认证服务如下:

import { Injectable } from '@angular/core';

@Injectable()
export class SecretService 
{
    public get adalConfig(): any {
        return {
            tenant: 'xxxxxxxxxxxxxxx.onmicrosoft.com',
            clientId: 'xxxxyyyyzzzzaaaabbbb',
            redirectUri: window.location.origin + '/',
            postLogoutRedirectUri: window.location.origin + '/'
        };
    }
}

更改为下方,在成功验证后继续使用 URL:http://localhost:31334/index.html/,并且不会导航到“上传”。之后,单击“上传”链接会显示“上传”页面,所有 CSS 和格式都完好无损。

export class SecretService 
    {
        public get adalConfig(): any {
            return {
                tenant: 'xxxxxxxxxxxxxxx.onmicrosoft.com',
                clientId: 'xxxxyyyyzzzzaaaabbbb',
                redirectUri: window.location.origin + '/index.html',
                postLogoutRedirectUri: window.location.origin + '/index.html'
            };
        }
    }

在没有身份验证的情况下单击按钮单独导航到路由this.router.navigate(["/upload"])会成功显示上传页面。

为了解决这个问题,我在 index.html 中添加了<base href="/index.html/">,并在身份验证组件中使用了window.location.origin + "/index.html"。同样在根组件构造函数中,我重定向到主组件为:this.router.navigate(['home']);

这会重新加载角度上下文,我无法维持状态,就像用户总是报告为未经身份验证一样,即使在成功认证后,我相信角度上下文正在重新加载。

请建议如何实现正确的行为。

【问题讨论】:

    标签: angular angular2-routing adal adal.js


    【解决方案1】:

    尝试在 index.html<head> 中添加 <base href="/index.html/">

    【讨论】:

    • 我添加了<base href="/index.html/"> 以隐藏 index.html 使其不会出现在 URL 中。但是,在成功验证后,我停留在根 url `localhost:31334` 上并且没有重定向到正确的路径。在 getAdal() 方法中,我更改为:redirectUri: this.router.navigate['upload'], postLogoutRedirectUri: this.router.navigate['home'] 在成功验证后仍在根 url 上。 redirectUri: '' 也没什么区别,我被重定向到 root 而不是“上传”路由
    • 添加<base href> 不会隐藏/index.html 的出现,它告诉路由器将基本URL 视为yourdomain.com/index.html
    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 2018-03-14
    • 1970-01-01
    • 2014-09-22
    • 2018-09-06
    • 1970-01-01
    • 2021-09-17
    • 2021-05-16
    相关资源
    最近更新 更多