加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2重定向到登录页面

发布时间:2020-12-17 08:58:15 所属栏目:安全 来源:网络整理
导读:我来自Asp.Net MVC世界,用户试图访问他们没有被授权的页面被自动重定向到登录页面。 我试图在Angular2上重现这种行为。我来到了@CanActivate装饰器,但它导致组件根本不呈现,没有重定向。 我的问题如下: Angular2提供了一种实现这种行为的方法吗? 如果是
我来自Asp.Net MVC世界,用户试图访问他们没有被授权的页面被自动重定向到登录页面。

我试图在Angular2上重现这种行为。我来到了@CanActivate装饰器,但它导致组件根本不呈现,没有重定向。

我的问题如下:

> Angular2提供了一种实现这种行为的方法吗?
>如果是,如何?这是一个好的做法吗?
>如果没有,在Angular2中处理用户授权的最佳做法是什么?

更新:我已经发布了一个完整的骨骼 Angular 2 project with OAuth2 integration在Github上显示下面提到的指令在行动。

一种方法是通过使用指令。与Angular 2组件不同,Angular 2组件基本上是您在页面中插入的新HTML标记(带有关联代码),属性指令是您放在标记中的属性,会导致某些行为发生。 Docs here。

您的自定义属性的存在导致事情发生在您放置指令的组件(或HTML元素)。考虑我用于我当前的Angular2 / OAuth2应用程序的这个指令:

import {Directive,OnDestroy} from 'angular2/core';
import {AuthService} from '../services/auth.service';
import {ROUTER_DIRECTIVES,Router,Location} from "angular2/router";

@Directive({
    selector: '[protected]'
})
export class ProtectedDirective implements OnDestroy {
    private sub:any = null;

    constructor(private authService:AuthService,private router:Router,private location:Location) {
        if (!authService.isAuthenticated()) {
            this.location.replaceState('/'); // clears browser history so they can't navigate with back button
            this.router.navigate(['PublicPage']);
        }

        this.sub = this.authService.subscribe((val) => {
            if (!val.authenticated) {
                this.location.replaceState('/'); // clears browser history so they can't navigate with back button
                this.router.navigate(['LoggedoutPage']); // tells them they've been logged out (somehow)
            }
        });
    }

    ngOnDestroy() {
        if (this.sub != null) {
            this.sub.unsubscribe();
        }
    }
}

这使我使用我写的身份验证服务,以确定用户是否已经登录,并且订阅认证事件,以便它可以踢出用户,如果他或她注销或超时。

你可以做同样的事情。您将创建一个像我的指令,检查是否存在必要的Cookie或其他状态信息,指示用户已通过身份验证。如果他们没有您正在寻找的那些标志,将用户重定向到您的主要公共页面(像我一样)或您的OAuth2服务器(或任何)。您可以将该directive属性放在任何需要保护的组件上。在这种情况下,它可能被称为保护,像在上面粘贴的指令。

<members-only-info [protected]></members-only-info>

然后,您需要将用户导航/重定向到应用程序中的登录视图,并在那里处理身份验证。您必须将当前路线更改为您想要的路线。所以在这种情况下,您可以使用依赖注入在指令的constructor()函数中获取一个Router object,然后使用navigate()方法将用户发送到您的登录页面(如上例所示)。

这假设你有一系列路由在某个地方控制< router-outlet>标签看起来像这样,也许:

@RouteConfig([
    {path: '/loggedout',name: 'LoggedoutPage',component: LoggedoutPageComponent,useAsDefault: true},{path: '/public',name: 'PublicPage',component: PublicPageComponent},{path: '/protected',name: 'ProtectedPage',component: ProtectedPageComponent}
])

如果您需要将用户重定向到外部网址(例如OAuth2服务器),则您的指令会执行以下操作:

window.location.href="https://myserver.com/oauth2/authorize?redirect_uri=http://myAppServer.com/myAngular2App/callback&response_type=code&client_id=clientId&scope=my_scope

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读